假設winform有一個按鈕和一個控件secondPic_1,現需求如下:
點擊按鈕實現鼠標自動移動到secondPic_1中央部位,點擊鼠標左鍵,並模擬鍵盤輸入‘M’。
#region 鼠標、鍵盤點擊
[DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
public static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
const int KEYEVENTF_KEYUP = 0x0002;
//模擬鼠標點擊
[System.Runtime.InteropServices.DllImport("user32")]
private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
//模擬鍵盤點擊
[DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
public static extern int PostMessage(IntPtr hWnd, int Msg, Keys wParam, int lParam);
//移動鼠標
const int MOUSEEVENTF_MOVE = 0x0001;
//模擬鼠標左鍵按下
const int MOUSEEVENTF_LEFTDOWN = 0x0002;
//模擬鼠標左鍵擡起
const int MOUSEEVENTF_LEFTUP = 0x0004;
//標示是否採用絕對座標
const int MOUSEEVENTF_ABSOLUTE = 0x8000;
//模擬鼠標右鍵按下
const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
//模擬鼠標右鍵擡起
const int MOUSEEVENTF_RIGHTUP = 0x0010;
#endregion
/// <summary>
/// 獲取控件相對於屏幕左上角的位置
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
private Point LocationOnClient(Control c)
{
Point retval = new Point(0, 0);
do
{
retval.Offset(c.Location);
c = c.Parent;
}
while (c != null);
return retval;
}
/// <summary>
/// 點擊按鈕,鼠標自動移動到某個控件,左擊控件並鍵入鍵盤M鍵
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pictureBox20_Click(object sender, EventArgs e)
{
//獲取電腦分辨率
int sceenHeight = Screen.PrimaryScreen.Bounds.Height;
int screenWeight = Screen.PrimaryScreen.Bounds.Width;
//獲取控件的位置
Point screen = LocationOnClient(secondPic_1);
Point screenP = new Point(screen.X + secondPic_1.Size.Width / 2, screen.Y + secondPic_1.Size.Height / 2);
Console.WriteLine("相對屏幕:" + screenP.X + " " + screenP.Y);
//將鼠標移動到控件的位置上,模擬鼠標左擊
mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, screenP.X * 65536 / screenWeight, screenP.Y * 65536 / sceenHeight, 0, 0);
//模擬鍵盤輸入
keybd_event(Keys.M, 0, 0, 0);
}