SendKeys to a specific program without it being in focus

Omney Pixel picture Omney Pixel · Feb 28, 2017 · Viewed 9.2k times · Source

I am trying to use sendkeys, but send it to a non focused program. For example, I want to use sendkeys to Notepad - Untitled, without it being focused. Sorry if it's unclear, I will elaborate. My current code is this:

        string txt = Regex.Replace(richTextBox3.Text, "[+^%~()]", "{$0}");

        System.Threading.Thread.Sleep(1000);
        SendKeys.Send(txt + "{ENTER}");

If I use SendMessage, would anyone care to show me an example of what I should do? I don't find anything I found online very useful for my issue.

Answer

vbguyny picture vbguyny · Feb 28, 2017

The following code I found from a previous SO answer. The PostMessage API will send a Windows message to a specific Windows handle. The code below will cause the key down event to fire for all instances of Internet Explorer, without giving focus, simulating that the F5 key was pressed. A list of additional key codes can be found here.

static class Program
{
    const UInt32 WM_KEYDOWN = 0x0100;
    const int VK_F5 = 0x74;

    [DllImport("user32.dll")]
    static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

    [STAThread]
    static void Main()
    {
        while(true)
        {
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)
                PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);

            Thread.Sleep(5000);
        }
    }
}