Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

c# - Send combination of keystrokes to background window

After a lot of research on Stackoverflow 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
        }
    }                           
}

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...