将键击发送到程序,即使它在后台使用c#

Sen*_*ncy 5 c# winapi desktop-application winforms keystrokes

我想将关键笔划发送到程序,即使它在后台运行.但我只能这样做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);
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)

但对于所有其他应用程序,我不能发送按键,如果它在后台.因为我不知道lpszClass那个程序(我认为这是该程序中输入区域的userControl名称.对于NotePad来说,它是"edit".我发现这个上网).

对于所有其他应用程序我正在做的是,将应用程序放到前台,然后发送密钥,然后再次获取我的程序前台.我需要我的程序始终作为前台运行.

[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

但这种方式不起作用.一些关键错过了,程序前景 - >背景 - > foregound->背景......喜欢它的舞蹈......

如果在后台运行,如何将密钥发送到其他应用程序.或者有没有找到lpszClass程序的方式/来源?

对不起,如果我错过了任何必要的信息.这是一个很大的应用程序.我这里只发布了必需的部分.如果有人需要任何其他信息,请询问.

Rei*_*ica 1

您也许可以使用WinSpy++lpszClass等检查工具找出程序的结构。它为您提供了一个十字准线,您可以将其拖动并放置在所需的控件上。这能够轻松地为我提供记事本的“编辑”类名称。

如果不起作用,请单击 WinSpy++ 右下角的“更多>>”按钮,然后单击“查找”按钮查看控件层次结构;您可能需要将 WM_KEYDOWN 消息发送到父控件或子控件之一。