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.

3

2 Answers 2

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);
        }
    }
}
1
  • 1
    What about multiple keys like CTRL+F1 ??
    – HeavenHM
    Nov 16, 2021 at 4:33
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);
        }
2
  • PostMessage takes an int but your code below is trying to pass in an IntPtr which means this code does not compile
    – NibblyPig
    Oct 14, 2022 at 11:46
  • @NibblyPig Did u try it? In my case it works fine :)
    – Deniz
    Oct 18, 2022 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.