即使程序在后台运行,我也想将击键发送到程序。但我只能为这样的记事本做到这一点,
[DllImport("user32.dll")]
protected static extern byte VkKeyScan(char ch);
[DllImport("user32.dll", SetLastError = true)]
protected static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("User32.Dll", EntryPoint = "PostMessageA")]
protected static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
char Key = // key value to send
IntPtr hWnd = FindWindowEx(_handle, IntPtr.Zero, "edit", null); // _handle is the windows handle of the program (here its notepad)
PostMessage(hWnd, WM_KEYDOWN, VkKeyScan(Key), 0);
但是对于所有其他应用程序,如果它在后台,我将无法发送击键。由于我不知道该lpszClass
程序的名称(我认为这是该程序中键入区域的 userControl 名称。对于记事本来说是"edit"
。我在网上冲浪时发现了这个)。
对于所有其他应用程序,我正在做的是将应用程序置于前台,然后发送密钥,然后再次将我的程序置于前台。我需要我的程序始终作为前台运行。
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
SetForegroundWindow(_handle); // _handle is the windows handle of the program
System.Threading.Thread.Sleep(50); // Waiting few milliseconds till application coming to foreground.
wsh.SendKeys(Key.ToString(), ref wait); // wsh is WshShellClass wsh= new WshShellClass();
SetForegroundWindow(_mainHandle); // _mainHandle is the windows handle of my application
但这种方式行不通。一些键丢失,程序前景->背景->前景->背景......就像它的舞蹈......
如果它在后台运行,如何将密钥发送到其他应用程序。或者有什么方法/来源可以找到lpszClass
一个程序?
抱歉,如果我错过了任何必需的信息。这是一个大型应用程序。我在这里只发布了需要的部分。如果有人需要任何其他信息,请询问。