如果鼠标下的像素颜色具有特定颜色,我的程序会在Windows窗体中自动执行单击操作。现在的问题是,有时候,也许是在一个小时之后,或者也许是在程序运行5个小时之后(并且工作似乎完全正常),整个系统(OS)崩溃了。有时,我能够捕获AccessViolationException。 我非常确定崩溃与我必须调用的非托管方法有关,因为单击鼠标并获取屏幕像素的颜色。但我不能为它找出错误的地狱。我使用以下代码进行鼠标点击:
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
static extern void mouse_event(uint dwFlags, uint dx, uint dy,
uint dwData, UIntPtr dwExtraInfo);
private const uint MOUSEEVENTF_LEFTDOWN = 0x02;
private const uint MOUSEEVENTF_LEFTUP = 0x04;
public void DoMouseClick()
{
//Call the imported function with the cursor's current position
uint X = (uint)Cursor.Position.X;
uint Y = (uint)Cursor.Position.Y;
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, UIntPtr.Zero);
}
为了获得像素的颜色,我使用它:
[DllImport("user32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("gdi32.dll")]
static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
static public System.Drawing.Color GetPixelColor(int x, int y)
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, x, y);
ReleaseDC(IntPtr.Zero, hdc);
Color color = Color.FromArgb((int)(pixel & 0x000000FF),
(int)(pixel & 0x0000FF00) >> 8,
(int)(pixel & 0x00FF0000) >> 16);
return color;
}
这两种方法大多是从互联网上复制粘贴的。我在Windows Forms中使用前面提到的这些东西。 Forms.Timer一直运行,不知道是否重要...在64位Windows上运行此程序,程序是针对目标x86编译的。
编辑:我非常确定非托管方法是否负责的原因是AccessViolationException的堆栈跟踪看起来的方式(“bei”=“at”):
bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
bei System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
bei System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
bei System.Windows.Forms.Application.Run(Form mainForm)
bei McDonaldsVote.Program.Main(String[] args) in C:\Users\Chris\Documents\Visual Studio 2008\Projects\McDonaldsVote\McDonaldsVote\Program.cs:Zeile 22.