4

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.

Omney Pixel
  • 47
  • 1
  • 2
  • 5
  • 1
    Possible duplicate of [Sending keys to inactive application in C#/.NET](http://stackoverflow.com/questions/1584767/sending-keys-to-inactive-application-in-c-net) – Raymond Chen Feb 28 '17 at 00:47
  • 3
    Better would be to use UI Automation. – Raymond Chen Feb 28 '17 at 00:47
  • 1
    @RaymondChen I tried looking at SendMessage, but it didn't make any sense to me. If possible, can I get more help rather than a microsoft page? – Omney Pixel Feb 28 '17 at 00:47

2 Answers2

9

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);
        }
    }
}
Community
  • 1
  • 1
vbguyny
  • 1,170
  • 1
  • 10
  • 29
1

It took me a while to figure it out for myself

Also here a usefull list of Virtual Key Codes

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

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

        private void button1_Click(object sender, EventArgs e)
        {
            const int WM_SYSKEYDOWN = 0x0104;
            const int VK_RETURN = 0x0D;

            IntPtr WindowToFind = FindWindow(null, "Notepad - Untitled"); // Window Titel

            PostMessage(WindowToFind, WM_SYSKEYDOWN, VK_RETURN, 0);
        }
Deniz
  • 429
  • 1
  • 4
  • 19