Search code examples
windowswinapiexternalsendkeys

How to activate some window from external application in windows?


I want to send some keystroke to the external application, and it's work fine, but when I try to send keystroke to the child window of same external application, for some reason that doesn't work, so I need help. Let's say that we want to print clipboard text from notepad, and want to do it at one step. At code that will look like this.

        #include <windows.h>
    #include <stdio.h>
    #include <iostream.h>
    using namespace std;

    int main(int argc, char* argv[]){
        WinExec("notepad", 1);
        Sleep(1000);
        HWND handle = FindWindow("notepad",0);  // it's handling as well
        SetForegroundWindow(handle);        
        keybd_event(VK_CONTROL, 0, 0, 0);   // simulate CTRL down
        keybd_event(VkKeyScan('V'), 0, 0, 0);
        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); 
        Sleep(500);
        keybd_event(VK_CONTROL, 0, 0, 0);   // simulate CTRL down
        keybd_event(VkKeyScan('P'), 0, 0, 0);
        keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0); // simulate CTRL up
        Sleep(1000);
        HWND handle1 = FindWindow(0, "Print");  // it wann't find "Print" window
        SetForegroundWindow(handle1);
        keybd_event(VK_MENU, 0, 0, 0); // simulate ALT down
        keybd_event(VkKeyScan('P'), 0, 0, 0);
        keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);
        return 0;
    }

But it want to send ALT+P to "Print" window, why? Final goal is to make little macro that send to application keystorkes (on any windows child, or parent..) OS: WIN 7 64bit


Solution

  • You can probably make the existing code (sort of) work by simply removing these lines:

    HWND handle1 = FindWindow(0, "Print");  // it wann't find "Print" window
    SetForegroundWindow(handle1);
    

    Remember that faked input goes to the thread which has the input focus and when you show the print dialog in Notepad, that dialog will gain the input focus. You simply do not need to set the focus, the system will do that for you.

    However, the approach you are taking is incredibly brittle. I suspect that you would be far better served by using something like UI Automation.