Я использую IronPython 2.6 и WebbrowserControl в форме TridentForm. Используется для отображения отчетов и т. Д.
Основная форма, LaunchForm, имеет кнопку с обработчиком события OnClick. Этот обработчик событий устанавливает некоторые вещи, а затем запускает BackgroundWorker. Фоновый работник завершает работу, и в этом обратном вызове он создает экземпляр TridentForm, показывает его и т. Д. И т. Д.
Теперь это работает отлично, вот сокращенный текущий код:
class LaunchForm(Form):
def __init__(self):
#blah blah, InitilizeComponents(), blah
self.form_splash = None
self.form_report = None
self._report_worker = BackgroundWorker()
self._report_worker.DoWork += self.runReport
self._report_worker.RunWorkerCompleted += self.runReport_finished
def runReport_handler(self, sender, args):
self._report_worker.RunWorkerAsync(job_type)
log.debug("renReport_handler called on thread %s"%(Thread.CurrentThread.ManagedThreadId))
def runReport(self, sender, args): #run by a backgroundworker
#do stuff, doesn't matter
def runReport_finished(self, sender, args):
#error checking, etc
log.debug("reunReport_finished called on thread %s"%(Thread.CurrentThread.ManagedThreadId))
if not self.form_report:
log.debug("Creating TridentForm")
self.form_report = TridentForm()
log.debug("Getting TridentForm")
vf = self.form_report
Как видите, self.form_report (TridentForm) используется повторно после первого создания. Причина этого заключается в том, что между инструкциями журнала «Создание TridentForm» и «Получение TridentForm» до 7 секунд тратится (казалось бы) ничего. Журнал не говорит лжи. В любом случае, я предполагаю, что это время инициализации компонента для элемента управления ActvieX в IE.
Очевидно, я не хочу ждать 7 секунд.
Итак, я решил попробовать создать форму в конце runReport_handler - это заставит пользовательский интерфейс немного зависнуть, но фоновый поток работает, так что ничего страшного. Обратите внимание на записи в журнале об идентификаторах потоков - я подтвердил, что runReport_handler и runReport_finished вызывают в одном потоке.
Итак, моя проблема: простое перемещение этого создания до конца runReport_handler дает мне несколько забавных необработанных исключений потоков:
Traceback (most recent call last):
File "C:\completely\unrelated\control\subclass\used\on\the\mainform.py", line 33, in OnMouseUp
TypeError: cannot access protected member OnMouseUp without a python subclass of Control
Microsoft.Scripting.ArgumentTypeException: cannot access protected member OnMouseUp without a python subclass of Control
at IronPython.Runtime.Types.BuiltinFunction.<>c__DisplayClass6.<MakeBuiltinFunctionDelegate>b__0(Object[] callArgs, Boolean& shouldOptimize)
at IronPython.Runtime.Types.BuiltinFunction.BuiltinMethodCaller`2.Call1(CallSite site, CodeContext context, TFuncType func, T0 arg0)
at Microsoft.Scripting.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.LightLambda.Run3[T0,T1,T2,TRet](T0 arg0, T1 arg1, T2 arg2)
at IronPython.Compiler.PythonCallTargets.OriginalCallTarget2(PythonFunction function, Object arg0, Object arg1)
at IronPython.Runtime.PythonFunction.FunctionCaller`2.Call2(CallSite site, CodeContext context, Object func, T0 arg0, T1 arg1)
at Microsoft.Scripting.UpdateDelegates.UpdateAndExecute4[T0,T1,T2,T3,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
at IronPython.Runtime.PythonFunction.FunctionCaller`2.Default1Call2(CallSite site, CodeContext context, Object func, T0 arg0, T1 arg1)
at CallSite.Target(Closure , CallSite , CodeContext , Object , Object )
at Microsoft.Scripting.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at IronPython.NewTypes.System.Windows.Forms.Control_13$14.OnMouseUp(MouseEventArgs )
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at IronPython.NewTypes.System.Windows.Forms.Control_13$14.WndProc(Message& )
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
и
Traceback (most recent call last):
File "C:\TridentForm.py", line 159, in TridentNavigating
TypeError: cannot access protected member OnMouseUp without a python subclass of Control
Microsoft.Scripting.ArgumentTypeException: cannot access protected member OnMouseUp without a python subclass of Control
at IronPython.Runtime.Types.BuiltinFunction.<>c__DisplayClass6.<MakeBuiltinFunctionDelegate>b__0(Object[] callArgs, Boolean& shouldOptimize)
at IronPython.Runtime.Types.BuiltinFunction.BuiltinMethodCaller`2.Call1(CallSite site, CodeContext context, TFuncType func, T0 arg0)
at Microsoft.Scripting.Interpreter.DynamicInstruction`4.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
at Microsoft.Scripting.Interpreter.LightLambda.Run3[T0,T1,T2,TRet](T0 arg0, T1 arg1, T2 arg2)
at IronPython.Runtime.PythonFunction.FunctionCaller`2.Call2(CallSite site, CodeContext context, Object func, T0 arg0, T1 arg1)
at CallSite.Target(Closure , CallSite , CodeContext , Object , Object )
at IronPython.NewTypes.System.Windows.Forms.Control_13$14.OnMouseUp(MouseEventArgs )
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at IronPython.NewTypes.System.Windows.Forms.Control_13$14.WndProc(Message& )
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Оба из которых не имеют никакого смысла. В качестве бонуса, теперь щелкнув по главной форме, вы получите это сообщение.
Ссылка на исключения:
строка 33 несвязанного элемента управления:
def OnMouseUp (self, e):
self.pressed = False
если self.image_down:
self.Invalidate ()
super (SimpleImageButton, self) .OnMouseUp (e) # умирает здесь. Да, это подкласс управления.
и код TridentForm:
def TridentNavigating (self, sender, e):
если e.Url! = self.dest_url и e.Url! = PLEASE_WAIT_URL: # здесь. Я - это Форма, которая, я думаю, является подклассом Контроля. Но, тем не менее, ни одна из вещей в этой строке не касается типов clr - self.dest_url является атрибутом python
Итак, я потерян.
В качестве альтернативы, если бы вы могли предложить способ «предварительной загрузки» TridentForm другим способом, это было бы здорово. Благодарю.
e.Cancel = true