将击键组合发送到后台窗口

问题描述:

在对*和google进行了大量研究之后,似乎很难使用它的句柄将击键组合发送到背景窗口.例如,我要发送CTRL +F.似乎Sendmessage不起作用,并且sendinput无效,因为窗口需要焦点.

After a lot of research on * and google, it seems that it's difficult to send a combination of keystroke to a background window using it's handle. For example, I want to send CTRL + F. It seems that Sendmessage doesn't work, and sendinput isn't effective because the window needs the focus.

所以我最后的想法是关于钩子:反正有什么方法可以使用这种方式发送组合?

So the my last thought is about hooking: is there anyway to use that way to send combination?

好,我找到了一种解决方法,但它不适用于所有应用程序.否则,它将与puTTY一起使用,我想通过按键组合来控制该程序.即使应用程序不集中精力,它也能正常工作.这样我就完成了!

Ok I found a workaround, but it doesn't work for all applications. Otherwise, it works with puTTY, the program I wanted to control with keystroke combination. And it works even if the application isn't focused. So I'm done now!

class SendMessage
{
[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

public static void sendKeystroke()
{
    const uint WM_KEYDOWN = 0x100;
    const uint WM_KEYUP = 0x0101;

    IntPtr hWnd;
    string processName = "putty";
    Process[] processList = Process.GetProcesses();

    foreach (Process P in processList)
    {
        if (P.ProcessName.Equals(processName))
        {
            IntPtr edit = P.MainWindowHandle;
            PostMessage(edit, WM_KEYDOWN, (IntPtr)(Keys.Control), IntPtr.Zero);
            PostMessage(edit, WM_KEYDOWN, (IntPtr)(Keys.A), IntPtr.Zero);
            PostMessage(edit, WM_KEYUP, (IntPtr)(Keys.Control), IntPtr.Zero);
        }
    }                           
}

}