向外部程序发送按键(或组合键)
我想在A程序正常操作时,由我的程序C向最小化的B程序发送按键或组合键
(譬如在使用Word时,有一个最小化到任务栏上的IE窗口,我想刷新(F5)或保存(CTRL+S)它)
我的想法是,先找到窗口的句柄,然后用Sendmessage向该窗口发送按键消息:
- int WM_KEYDOWN = 0X100;//按键按下时
- int WM_KEYUP = 0X101;//按键放开时
- int WM_SYSCHAR = 0X106;
- int WM_SYSKEYUP = 0X105;
- int WM_SYSKEYDOWN = 0X104;//按键按下时,且ALT键也被按着
- int WM_CHAR = 0X102;//按键按下时
- SendMessage(lhwnd,WM_SYSKEYDOWN,0,0);//AlT按下,lhwnd为查找到的其它窗口句柄。
- SendMessage(lhwnd,WM_KEYDOWN,83,0);//S键按下。
- SendMessage(lhwnd,WM_KEYUP,83,0);
- SendMessage(lhwnd,WM_SYSKEYUP,0,0);
感觉自己的想法还是可行的,只是什么地方操作有问题~~
====================================================== 将notepad最小化,可以发送。
- [DllImport("user32")]
- public static extern unsafe int FindWindow(string sClassName, string WindowName);
- [DllImport("user32")]
- public static extern unsafe bool SetForegroundWindow(int hWnd);
- private bool AppActivate(string sWindowName)
- {
- int hwind = FindWindow(null, sWindowName);
- if(hwind == 0)
- return false;
- SetForegroundWindow(hwind);
- return true;
- }
- if(AppActivate("notepad"))
- {
- System.Windows.Forms.SendKeys.SendWait("%(f)o");
- //....
- }
how to use keybd_event in C#
- using System;
- using System.Runtime.InteropServices;
- using System.Text;
- namespace ConsoleApplication8{
- class Class1{
- [STAThread]
- static void Main(string[] args){
- // Display current status of keys.
- Console.WriteLine(
- "**BEFORE**/r/nCAP: {0}/r/nSCR: {1}/r/nNUM: {2}",
- Keyboard.GetState(VirtualKeys.VK_CAPITAL)?"ON":"OFF",
- Keyboard.GetState(VirtualKeys.VK_SCROLL)?"ON":"OFF",
- Keyboard.GetState(VirtualKeys.VK_NUMLOCK)?"ON":"OFF"
- );
- //Toggle all the keys:
- Keyboard.SetState(VirtualKeys.VK_CAPITAL, !Keyboard.GetState(VirtualKeys.VK_CAPITAL));
- Keyboard.SetState(VirtualKeys.VK_SCROLL, !Keyboard.GetState(VirtualKeys.VK_SCROLL));
- Keyboard.SetState(VirtualKeys.VK_NUMLOCK, !Keyboard.GetState(VirtualKeys.VK_NUMLOCK));
- // Display new status of keys.
- Console.WriteLine(
- "/r/n**AFTER**/r/nCAP: {0}/r/nSCR: {1}/r/nNUM: {2}",
- Keyboard.GetState(VirtualKeys.VK_CAPITAL)?"ON":"OFF",
- Keyboard.GetState(VirtualKeys.VK_SCROLL)?"ON":"OFF",
- Keyboard.GetState(VirtualKeys.VK_NUMLOCK)?"ON":"OFF"
- );
- Console.ReadLine();
- }
- }
- public enum VirtualKeys: byte{
- VK_NUMLOCK = 0x90,
- VK_SCROLL = 0x91,
- VK_CAPITAL = 0x14
- }
- class Keyboard{
- const uint KEYEVENTF_EXTENDEDKEY = 0x1;
- const uint KEYEVENTF_KEYUP = 0x2;
- [DllImport("user32.dll")]
- static extern short GetKeyState(int nVirtKey);
- [DllImport("user32.dll")]
- static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
- public static bool GetState(VirtualKeys Key){
- return (GetKeyState((int)Key)==1);
- }
- public static void SetState(VirtualKeys Key, bool State){
- if(State!=GetState(Key)){
- keybd_event((byte)Key, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
- keybd_event((byte)Key, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
- }
- }
- }
- }