【发布时间】:2014-08-23 08:42:46
【问题描述】:
在我正在做的 form1 构造函数中:
buttonSnap.Enabled = false;
backgroundWorker1.RunWorkerAsync();
然后我有一个按钮点击:
private void buttonSnap_Click(object sender, EventArgs e)
{
ClearGraphics = true;
this.listBoxSnap.Items.Clear();
this.pictureBoxSnap.Image = null;
backgroundWorker1.RunWorkerAsync();
buttonSnap.Enabled = false;
}
在后台工作人员执行事件中,我将每个项目添加到列表框中,每个项目都是一个捕获的窗口:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (this.IsHandleCreated)
{
listBoxSnap.Invoke(new MethodInvoker(delegate { this.listBoxSnap.Items.Add("Minimized Windows"); }));
listBoxSnap.Invoke(new MethodInvoker(delegate { this.listBoxSnap.Items.AddRange(WindowSnap.GetAllWindows(true, true).ToArray()); }));
}
}
catch (Exception ee)
{
string t = "exception " + ee.ToString();
}
}
这是 WindowSnap.cs 类的链接:
这是 WindowSnapCollection.cs 的链接:
在 WindowSnap.cs 中有 GetallWindows 方法:
public static WindowSnapCollection GetAllWindows(bool minimized, bool specialCapturring)
{
windowSnaps = new WindowSnapCollection();
countMinimizedWindows = minimized;//set minimized flag capture
useSpecialCapturing = specialCapturring;//set specialcapturing flag
EnumWindowsCallbackHandler callback = new EnumWindowsCallbackHandler(EnumWindowsCallback);
EnumWindows(callback, IntPtr.Zero);
return new WindowSnapCollection(windowSnaps.ToArray(), true);
}
现在DoWork事件有时会抛出异常就行了:
listBoxSnap.Invoke(new MethodInvoker(delegate { this.listBoxSnap.Items.AddRange(WindowSnap.GetAllWindows(true, true).ToArray()); }));
例外是:
在创建窗口句柄之前,不能对控件调用 Invoke 或 BeginInvoke
完整的异常消息:
System.InvalidOperationException was caught
Message=Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at MinimizeCapture.Form1.backgroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in c:\Temp\Capture\Form1.cs:line 81
InnerException:
第 81 行是:
listBoxSnap.Invoke(new MethodInvoker(delegate { this.listBoxSnap.Items.Add("Minimized Windows"); }));
现在我在后台添加了工作事件 try and catch ,有时它会在字符串 t...in catch 处停止。然后我添加了这个:
如果(this.IsHandleCreated)
所以现在有时它会做同样的问题,但不会停止捕获并抛出异常。 有时仍然存在相同的问题,但有时会出现异常描述的问题。
This : if (this.IsHandleCreated) 没有解决它。
【问题讨论】:
-
如果这是您的完整 _DowWork() 方法,那么您不需要 Bgw。