Thread: catching keys when lost focus

  1. #1
    Android geek@02's Avatar
    Join Date
    Mar 2004
    Location
    Kurunegala Colony, Sri Lanka, Sri Lanka
    Posts
    470

    catching keys when lost focus

    Hi!
    Is it possible to catch users key presses from a MFC app, even when its window has lost the focus?
    For example, a MFC app is running in the background, and the user types something in notepad- can the MFC program read what user types? If it’s possible, please tell me how to do it.
    Thanks.

  2. #2
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    New York
    Posts
    1,905
    I believe the best way would be to use asynchronous key checking using the function:
    GetAsyncKeyState

    macro:
    Code:
     #define KEY_DOWN(vk_code)	((GetAsyncKeyState((vk_code))&0x8000 ? 1:0))
    Probably not the best way to do it, as you'll need to have a loop sitting in the background checking the state every few milliseconds. I'd suggest putting Sleep function in there so the program doesn't hog the cpu.

    so you might do something like this:

    Code:
     while(isGoing)
     {
     	 Sleep(100);
     	 if(KEY_DOWN(VK_ESCAPE))
     	 {
     			// do stuff!
     	 }
     }
    or something like that

    -hope that helps

  3. #3
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401
    I'm thinking you could handle the WM_KILLFOCUS message, and hook into the window that took the focus from you, and basically follow the focus around wherever it goes. It's not too elegant, but it sure is kinda cool.
    [email protected]
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simulate Keys with a Keyboard Hook
    By guitarist809 in forum Windows Programming
    Replies: 3
    Last Post: 11-14-2008, 08:14 PM
  2. blocking or passing keys with global hook
    By pmouse in forum Windows Programming
    Replies: 4
    Last Post: 08-29-2007, 02:54 PM
  3. Changing focus in an MFC Application
    By rangalo in forum Windows Programming
    Replies: 2
    Last Post: 06-20-2005, 06:21 AM
  4. Focus lost...
    By Devil Panther in forum Windows Programming
    Replies: 6
    Last Post: 04-10-2004, 03:54 AM
  5. Focus & Always-On-Top :: MFC
    By kuphryn in forum Windows Programming
    Replies: 2
    Last Post: 06-13-2002, 05:44 PM