【发布时间】:2011-06-08 16:36:58
【问题描述】:
即使程序在后台运行,我也想将击键发送到程序。但我只能像这样对notepad做到这一点,
[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(我认为这是该程序中输入区域的用户控件名称。对于记事本,它是"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?
抱歉,如果我错过了任何必需的信息。这是一个大型应用程序。我在这里只发布了需要的部分。如果有人需要任何其他信息,请询问。
【问题讨论】:
-
SO 已经有数百个关于此的问题,不知道您是如何错过的。无论你做什么来让注意力转移回来,都不要这样做。
标签: c# winforms winapi desktop-application keystrokes