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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…