Question Check window focus?

Chicken

New member
Joined
Aug 29, 2009
Messages
4
Programming Experience
Beginner
Hello, I'm fairly new to VB.NET coding (I use Visual Basic Express Edition 2008). I have been trying to find out how to find out how to do this for a while now, it would be great if you guys could help as I am pretty frustrated :mad:

How would you code it so that, if a specific window (Let's say notepad) is not focused, then *whatever*?

I've looked up getfocus, getwindowthreadprocessid, and a bunch of other codes but can't find it.

And, I'm not looking for "If me.focus = false then", I need to do it on a different window.

Thanks for your help,

-Chicken
 
Please post in the most appropriate forum for the topic of the thread. This is not an IDE question so it doesn't belong in the VS.NET forums. Thread moved.

GetForegroundWindow will give you the handle of the window that has focus. You can then test that window in whatever way is appropriate, e.g. get its caption, and if it's not the one you're interested in then you can do *whatever*.
 
Well.. Yeah getforegroundwindow gives me the handle (a 19 digit number), but whenever I restart the whole thing like exit out of notepad then open it back up, the handle changes.

How would I defeat that?

Thanks again =]
 
The handle doesn't actually change. If you close the window then it ceases to exist, and if you then create a new window it will have a different handle. There's no way to "defeat" that. You just have to get the handle of the specific window you're interested in when you're interested in it.
 
I think you've misunderstood something. The handle is not a specific value associated with Notepad or whatever that you can hard-code into your app.

Every window has a handle. When I say "window" here I don't just mean what we think of as forms. All the buttons, text boxes, etc. are also windows. When the OS creates a window it simply takes the next available handle and assigns it to that window. The handle is then a key that the OS uses to identify that specific window for as long as it exists. Once that window is destroyed its handle is added back to the pool and will be used again for some other window in future, over and over.

So, you are not doing here what you think you are doing. What you need to do is get the handle of the foreground window at run time, whenever it is that you need to use it. You then use that handle to get information about the window, e.g. its caption, and determine whether it is the window you are interested in. Either it is or it's not, and you proceed accordingly.

Your original request example was to do something if the Notepad window has focus. In general terms, to achieve that you need to:

Get the handle of the foreground window,
check whether the window that corresponds to that handle is a Notepad window,
if it is then do something.
 
Back
Top