CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9

Threaded View

  1. #1
    Join Date
    Jul 2009
    Posts
    5

    Sending keystrokes to other *non-focus* application

    In order to send keystorkes or mouse clicks to other application that is not in focus, I found
    in the internet the concept of using SendInput while attaching my application thread to the application I want to control. Here is the short console program code for writing the letter 'g' on the notepad program.
    But still problem - it doesn't put the letter on the notepad... why?



    Code:
    #include "stdafx.h"
    #include "conio.h"
    #include "windows.h"
    
    void sendKey(WORD wVk)
    {
    	INPUT input[2];
    
    	input[0].ki.wVk = wVk;
    	input[0].ki.wScan = 0;
    	input[0].ki.dwFlags = 0; //press down;
    	input[0].ki.time = 0;
    	input[0].ki.dwExtraInfo = 0;
    	input[0].type = INPUT_KEYBOARD;
    
    	input[1].ki.wVk = wVk;
    	input[1].ki.wScan = 0;
    	input[1].ki.dwFlags = KEYEVENTF_KEYUP;
    	input[1].ki.time = 0;
    	input[1].ki.dwExtraInfo = 0;
    	input[1].type = INPUT_KEYBOARD;
    
    	SendInput(2, input, sizeof(INPUT));
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	TCHAR	sText[1024];
    	HWND	hTargetWnd;
    	DWORD   processID;
    	DWORD	threadID;
    	
    	
    	HWND hNotepadWnd = FindWindow(NULL,  L"Untitled - Notepad");
        hTargetWnd=FindWindowEx(hNotepadWnd,NULL,L"Edit",NULL);
    	threadID = GetWindowThreadProcessId(hTargetWnd , &processID);	
    	if(hTargetWnd)
    	{
    		wsprintf(sText, L"Target window found\nWindow = %p\nprocessID = %x\nThreadID = %x\n",hTargetWnd,processID,threadID);
    		wprintf(L"%s",sText);
    		
    			  if(AttachThreadInput( GetCurrentThreadId(), threadID,true))
    			  {
    				sendKey('G');
    				AttachThreadInput(GetCurrentThreadId(),threadID,   false);
    			  }
    	}
    	else
    	{
    		wprintf(L"Window Notepad wasn't found\n");
    	}
    
    	// if there was SendInput, it also should be seen here
    	while(_kbhit())
    	{
    		wprintf(L"%c",getch());
    	}
    
    	// wait for keystroke to exit
    	while(!_kbhit());
    
    	return 0;
    }
    Last edited by Marc G; August 4th, 2009 at 07:30 AM. Reason: Added code tags

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured