Search code examples
c#windowtitlehandle

Return Window handle by it's name / title


I can't solve this problem. I get an error:

The name 'hWnd' does not exist in the current context

It sounds very easy and probably is... sorry for asking so obvious questions.

Here's my code:

public static IntPtr WinGetHandle(string wName)
{
    foreach (Process pList in Process.GetProcesses())
    {
        if (pList.MainWindowTitle.Contains(wName))
        {
            IntPtr hWnd = pList.MainWindowHandle;
        }
    }
    return hWnd;
}

I tried with many different ways and each fails. Thanks in advance.


Solution

  • Update: See Richard's Answer for a more elegant approach.

    Don't forget you're declaring you hWnd inside the loop - which means it's only visible inside the loop. What happens if the window title doesn't exist? If you want to do it with a for you should declare it outside your loop, set it inside the loop then return it...

    IntPtr hWnd = IntPtr.Zero;
    foreach (Process pList in Process.GetProcesses())
    {
        if (pList.MainWindowTitle.Contains(wName))
        {
            hWnd = pList.MainWindowHandle;
        }
    }
    return hWnd; //Should contain the handle but may be zero if the title doesn't match
    

    Or in a more LINQ-y way....

    IntPtr? handle = Process
        .GetProcesses()
        .SingleOrDefault(x => x.MainWindowTitle.Contains(wName))
        ?.Handle;
    return handle.HasValue ? handle.Value : IntPtr.Zero