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.
The Win32 API provides no direct method for obtaining the window handle associated with a console application. However, you can obtain the window handle by calling FindWindow() . This function retrieves a window handle based on a class name or window name. Call GetConsoleTitle() to determine the current console title.
Hi Fardeen, a Window Handle is a unique identifier that holds the address of all the windows. This is basically a pointer to a window, which returns the string value. This window handle function helps in getting the handles of all the windows. It is guaranteed that each browser will have a unique window handle.
Currently there are several ways to get a ChildWindow handle; FindWindowEx (uses parent handle, plus window caption), GetWindow (uses parent handle, and Z-Order), and EnumChildWindows.
To change the window handle is a relatively quick and easy job – but only if you are replacing the window handle with the same style. It's essential to check that the new replacement window handle will fit into the holes on the uPVC window and that the spindle is the same size.
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
As an option to solve this problem:
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public IntPtr GetHandleWindow(string title)
{
return FindWindow(null, title);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With