14

How can I get the handle of a specific window using user32.dll?

Can someone give me a short example?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Alex
  • 351
  • 2
  • 6
  • 14

1 Answers1

24

Try the following:

// For Windows Mobile, replace user32.dll with coredll.dll
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

// Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter.

[DllImport("user32.dll", EntryPoint="FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

// You can also call FindWindow(default(string), lpWindowName) or FindWindow((string)null, lpWindowName)

You can use these declaration as follow

// Find window by Caption
public static IntPtr FindWindow(string windowName)
{
    var hWnd = FindWindow(windowName, null); 
    return hWnd;
}

Here is a Concise version of the code:

public class WindowFinder
{
    // For Windows Mobile, replace user32.dll with coredll.dll
    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    
    public static IntPtr FindWindow(string caption)
    {
        return FindWindow(String.Empty, caption);
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
crypted
  • 10,118
  • 3
  • 39
  • 52
  • and from main how can i access this methods? – Alex Apr 19 '11 at 07:27
  • and i call this method like: FindWindow("notepad") for example? – Alex Apr 19 '11 at 07:35
  • how do i know the handler is activated? Thx – Alex Apr 19 '11 at 07:36
  • Find window searches window from the Caption you see over the window, for example when you open Notepad it's default caption is "Notepad-Untitled" so your FindowWinow("notepad") does not match and returns no handle. – crypted Apr 19 '11 at 07:40
  • so i have to give as string the full name of the window that is opened? – Alex Apr 19 '11 at 07:42
  • 1
    how can I get the windowText annd the className? Because currently i have nullt o this elements. – Alex Apr 19 '11 at 07:48
  • 6
    I had to use `FindWindow(null, caption);` instead of `FindWindow(String.Empty, caption);` – Evariste May 10 '19 at 12:50
  • Is there a way for a Unity game to get its own window handle (of the main window)? E.g., if one wanted to compare it against GetForegroundWindow to see if something other than Unity jumped to the foreground? – Twisted on STRIKE at1687989253 May 28 '22 at 18:05