Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SendKeys to a specific program without it being in focus

Tags:

c#

sendkeys

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.

like image 553
Omney Pixel Avatar asked Feb 06 '23 00:02

Omney Pixel


2 Answers

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);
        }
    }
}
like image 144
vbguyny Avatar answered Feb 08 '23 17:02

vbguyny


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);
        }
like image 29
Deniz Avatar answered Feb 08 '23 17:02

Deniz