C#中winform完成主動觸發鼠標、鍵盤事宜的辦法。本站提示廣大學習愛好者:(C#中winform完成主動觸發鼠標、鍵盤事宜的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中winform完成主動觸發鼠標、鍵盤事宜的辦法正文
法式觸發鼠標、鍵盤事宜是C#法式設計中比擬罕見的功效,本文實例展現了C#中winform完成主動觸發鼠標、鍵盤事宜的辦法,有不錯的適用價值。詳細以下:
要想在C#法式中觸發鼠標、鍵盤事宜就必需要挪用windows函數。
1、鼠標事宜的觸發
1.援用windows函數mouse_event
/// <summary> /// 鼠標事宜 /// </summary> /// <param name="flags">事宜類型</param> /// <param name="dx">x坐標值(0~65535)</param> /// <param name="dy">y坐標值(0~65535)</param> /// <param name="data">轉動值(120一個單元)</param> /// <param name="extraInfo">不支撐</param> [DllImport("user32.dll")] static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
MouseEventFlag表現鼠標事宜的類型,可取多個列舉值組合。留意dx,dy參數,必需是相對坐標(0,0)~(65535,65535)中的一點。
/// <summary> /// 鼠標操作標記位聚集 /// </summary> [Flags] enum MouseEventFlag : uint { /// <summary> /// 鼠標挪動事宜 /// </summary> Move = 0x0001, /// <summary> /// 鼠標左鍵按下事宜 /// </summary> LeftDown = 0x0002, LeftUp = 0x0004, RightDown = 0x0008, RightUp = 0x0010, MiddleDown = 0x0020, MiddleUp = 0x0040, XDown = 0x0080, XUp = 0x0100, Wheel = 0x0800, VirtualDesk = 0x4000, /// <summary> /// 設置鼠標坐標為相對地位(dx,dy),不然為間隔最初一次事宜觸發的絕對地位 /// </summary> Absolute = 0x8000 }
2.挪用mouse_event函數,觸發鼠標事宜
/// <summary> /// 觸發鼠標事宜 /// </summary> /// <param name="x"></param> /// <param name="y"></param> private static void DoMouseClick(int x, int y) { int dx = (int)((double)x / Screen.PrimaryScreen.Bounds.Width * 65535); //屏幕分辯率映照到0~65535(0xffff,即16位)之間 int dy = (int)((double)y / Screen.PrimaryScreen.Bounds.Height * 0xffff); //轉換為double類型運算,不然值為0、1 mouse_event(MouseEventFlag.Move | MouseEventFlag.LeftDown | MouseEventFlag.LeftUp | MouseEventFlag.Absolute, dx, dy, 0, new UIntPtr(0)); //點擊 }
2、鍵盤事宜的觸發
1.援用windows函數keybd_event
/// <summary> /// 鍵盤事宜 /// </summary> /// <param name="bVk"> virtual-key code</param> /// <param name="bScan">hardware scan code</param> /// <param name="dwFlags"> flags specifying various function options</param> /// <param name="dwExtraInfo"> additional data associated with keystroke</param> [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
bvk為鍵值,例如回車13,bScan設置為0,dwFlags設置0表現按下,2表現抬起;dwExtraInfo也設置為0便可。
2.挪用keybd_event函數,觸發鍵盤事宜
上面的代碼演示觸發Ctrl+C組合鍵,履行復制操作。
keybd_event((byte)Keys.ControlKey, 0, 0, 0); keybd_event((byte)Keys.C, 0, 0, 0); keybd_event((byte)Keys.ControlKey, 0, 2, 0); keybd_event((byte)Keys.C, 0, 2, 0);
願望本文所述實例對年夜家的C#法式設計能起到必定的贊助感化。