C 實現的三種方式實現模擬鍵盤按鍵

2021-09-07 17:10:44 字數 1705 閱讀 5376

模擬按鍵在.net中有三種方式實現。

第一種方式:system.windows.forms.sendkeys 

組合鍵:ctrl = ^ 、shift = + 、alt = %

模擬按鍵:a

private void button1_click(object sender, eventargs e)

");}

模擬組合鍵:ctrl + a

private void button1_click(object sender, eventargs e)

");}

sendkeys.send // 非同步模擬按鍵(不阻塞ui)

sendkeys.sendwait // 同步模擬按鍵(會阻塞ui直到對方處理完訊息後返回)

第二種方式:keybd_event

模擬按鍵:a

[dllimport("user32.dll", entrypoint = "keybd_event", setlasterror = true)]

public static extern void keybd_event(keys bvk, byte bscan, uint dwflags, uint dwextrainfo);

private void button1_click(object sender, eventargs e)

模擬組合鍵:ctrl + a

public const int keyeventf_keyup = 2;

private void button1_click(object sender, eventargs e)

上面兩種方式都是全域性範圍呢,現在介紹如何對單個視窗進行模擬按鍵

模擬按鍵:a / 兩次

[dllimport("user32.dll", entrypoint = "postmessagea", setlasterror = true)]

public static extern int postmessage(intptr hwnd, int msg, keys wparam, int lparam);

public const int wm_char = 256;

private void button1_click(object sender, eventargs e)

模擬組合鍵:ctrl + a

如下方式可能會失效,所以最好採用上述兩種方式

public const int wm_keydown = 256;

public const int wm_keyup = 257;

private void button1_click(object sender, eventargs e)

{webbrowser1.focus();

keybd_event(keys.controlkey, 0, 0, 0);

keybd_event(keys.a, 0, 0, 0);

postmessage(webbrowser1.handle, wm_keydown, keys.a, 0);

keybd_event(keys.controlkey, 0, keyeventf_keyup, 0);

C 實現的三種方式實現模擬鍵盤按鍵

模擬按鍵在.net中有三種方式實現。第一種方式 system.windows.forms.sendkeys 組合鍵 ctrl shift alt 模擬按鍵 a private void button1 click object sender,eventargs e 模擬組合鍵 ctrl a priv...

C 實現的三種方式實現模擬鍵盤按鍵

組合鍵 ctrl shift alt 模擬按鍵 a private void button1 click object sender,eventargs e 模擬組合鍵 ctrl a private void button1 click object sender,eventargs e sendk...

C 三種方式實現模擬鍵盤按鍵

模擬按鍵在.net中有三種方式實現。第一種方式 system.windows.forms.sendkeys 組合鍵 ctrl shift alt 模擬按鍵 a private void button1 click object sender,eventargs e 模擬組合鍵 ctrl a priv...