Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get handle of a specific window using user32.dll

Tags:

c#

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

Can someone give me a short example?

like image 626
Alex Avatar asked Apr 19 '11 07:04

Alex


1 Answers

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);
    }
}
like image 88
crypted Avatar answered Nov 15 '22 11:11

crypted