问题
I'm trying to get a window handle on a child window in my process and the only information I have is the window class name. Are there any win32 functions I can use for that? I'm doing this from C#.
A bit more detail: This is a Visual Studio plugin, written in C#. So my process is visual studio, which has lots of windows. One of them has a window class "VsTipWindow". I don't know the immediate parent window of that window, all I have is the class name. Is there any way for me to get the window handle from just that?
回答1:
First off it should be noted that there is not a 1 to 1 relationship between windows and window classes, more than one window could use the same class.
I guess your only option is to call EnumChildWindows recursivly starting with the top level Visual Studio window (Or some other window higher in the window hierarchy if you know one that is a grandparent of the VsTipWindow window) In the callback function from EnumChildWindows you would call GetClassName and compare the string with VsTipWindow until you find the window.
Since you talked about unknown parent I'm assuming that you are after a child window, but if this window is a top level window, you need to use EnumWindows (And you should probably use GetWindowThreadProcessId to make sure you get the correct process also after you find a window with that classname)
(I'm sure .NET has functions that do the same thing as the native api, or you'd have to PInvoke)
回答2:
FindWindow is the Win32 call you want for this (or FindWindowEx if there's more than one window with that particular class name, and FindWindow isn't returning the one you're looking for).
回答3:
just additional information..
maybe it's useful to know that you can get the handle of a window from a point
WindowFromPoint
http://msdn.microsoft.com/en-us/library/ms633558(VS.85).aspx
回答4:
A Win32 window class is the generic implementation of a control, the handle of the windows is the instance of the control. So you will have multiple window handles with the same window class (e.g.: EDIT). Strictly speaking, a window class is the pointer to the window procedure.
Frameworks like .net (and even MFC) tend to share few window class for all the windows controls, and then they will dispatch to the appropriate controls (i.e. they have a single generic window procedure). This is the same also for big applications like Visual Studio or Office.
So this renders very difficult to detect a specific windows just through its window class. However, you can enumerate all the windows that have a specific windows class with FindWindow
, you will get also the window text that may help you. Using GetWindowThreadProcessId
you can detect if the window is belonging to Visual Studio.
来源:https://stackoverflow.com/questions/2943931/get-window-handle-from-window-class-name