If you need window coordinates for a window already in your process, there are other ways to get a window handle that don't require enumerating processes.
For WinForms windows, use the Handle
property.
System.Windows.Forms.Control ... Handle Property @ MSDN
For WPF applications, use WindowInteropHelper
System.Windows.Interop ... WindowInteropHelper Class @ MSDN
If you are trying to enumerate windows that you aren't able to access directly from .NET; say from a 3rd party control that creates a top-level window out of scope of your code, you may wish to enumerate via the win32 EnumWindows
function.
EnumWindows (Win32) @ MSDN
Signatures for P/Invoke for EnumWindows are available here:
User32.dll EnumWindows @ pinvoke.net
Added:
Looks like you want to enumerate all the windows & associated processes. Use EnumWindows
, then call GetWindowThreadProcessId
to get the associated Process & Unmanaged Thread ID for each window.
GetWindowThreadProcessId (Win32) @ MSDN
The P/Invoke signature is available here:
User32.dll GetWindowThreadProcessId @ pinvoke.net
Last, you can get a Process object via the static method GetProcessById
.
Process.GetProcessById @ MSDN
Added (#2):
Here's a short console program that can enumerate windows, process & thread ids. There are a few differences from your snippet.
- I use IntPtr, not HandleRef. As other people have pointed out, this may be confusing things for you.
- I didn't specify a
return
attribute. If this is required, you should be able to add it back in.
- I'm running as administrator; some things may run differently for you if you are running with user-level privileges.
C# Source Code Example @ gist.github
HandleRef( this, this.Handle );
You need to first get a handle to the window in question (and Process.Handle is likely not it). – Ed S. Feb 24 '11 at 0:27