Search code examples
c#sendkeys

Is there any way to send key(s) to other application without focus?


I have spent 3 days with this topic. All results that I found uses "SetForeground" and then, SendMessage or some APIs(keybd_event, kennedy(opensource) or etc). Of course, SendKeys does not send key(s) to specified process, I want to send key(s) to specified process that I know the PID or HWND.

I have no ideas of it, is it possible? If not, I'd rather implement with SetForeground that I unintended.

Any ideas?


Solution

  • I just found the solution.

    I didn't know about tab concept. The key point was tab handle, the real handle for key processing. If I use main window handle, it can process WM_CLOSE WM_SETTEXT (also SetWindowText(string)) but not WM_KEYDOWN. I imagined the sequence.

    1. keyboard stroke
    2. key event to the handle (main window handle)
    3. handle gives to received event WM_KEYDOWN / WM_CHAR / WM_KEYUP with VK_*

    So I must find the tab handle first.

    int getTabHandle() {
        int hwnd = 0;
        hwnd = FindWindowEx(hwnd , 0, "iexplore.exe", null);
        hwnd = FindWindowEx(hwnd , 0, "IEFrame", null);
        hwnd = FindWindowEx(hwnd , 0, "Frame Tab", null);
        hwnd = FindWindowEx(hwnd , 0, "TabWindowClass", null);
        hwnd = FindWindowEx(hwnd , 0, "Shell DocObject View", null);
        hwnd = FindWindowEx(hwnd , 0, "Internet Explorer_Server", null);
        return hwnd;
    }
    

    With this hwnd, I could send key without focus. Thanks.