Search code examples
c#apisendkeys

How to send a key to a process


I have started a process and want to post a message like PageDown key to it.

Here is the code for running the process.

Process.Start("chrome.exe", "D:/sample.htm");
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
    if (p.ProcessName == "chrome" && p.MainWindowTitle == "sample.htm - Google Chrome")
    {
       //how to Send a pagedown key to process p
    }
}

I created following class but i don't know why it doesn't work?

class KeyHandle
{
    private static Int32 WM_KEYDOWN = 0x100;
    private static Int32 WM_KEYUP = 0x101;

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("user32.dll", SetLastError = true)]
    static extern bool PostMessage(IntPtr hWnd, int Msg, System.Windows.Forms.Keys wParam, int lParam);

    public static void SendKey(IntPtr hWnd, System.Windows.Forms.Keys key)
    {
        PostMessage(hWnd, WM_KEYUP, key, 0);
    }


}

and call it this way

foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
{
    if (p.ProcessName == "chrome" && p.MainWindowTitle == "sample.htm - Google Chrome")
    {
         KeyHandle.SendKey(p.MainWindowHandle, Keys.PageDown);
    }
}

Solution

  • I rewrite your code using SendKeys API. I test it it works well

    foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses())
    {
        if (p.ProcessName == "chrome" && p.MainWindowTitle == "sample.htm - Google Chrome" &&
            p.MainWindowHandle != IntPtr.Zero)
        {
            SetForegroundWindow(p.MainWindowHandle);
            SendKeys.SendWait("{PGDN}");
        }
    }
    

    To declare the function SetForegroundWindow, use :

    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);
    

    List of keys