Is there a way to get the window handle (IntPtr) for a window after its launched from a C# app with Process.Start()?
Asked
Active
Viewed 2.2k times
11
-
Process p = Process.Start("Notepad"); p.WaitForInputIdle(); SetParent(p.MainWindowHandle, CBox.Handle); – Ebrahim Karam Mar 28 '21 at 00:24
4 Answers
27
If it's the main window you're after, Process.MainWindowHandle
will give you what you need.

Noldorin
- 144,213
- 56
- 264
- 302
8
Use
process.MainWindowHandle;
It probably is 0 when launching the app, so you might want to loop and sleep until it is filled up.

Jan Jongboom
- 26,598
- 9
- 83
- 120
-
1Hi Jan, For me, the handle is always zero and never goes to any other value, even after infinite looping. I use the following code: proc.StartInfo.FileName = @"C:\Documents and Settings\SUM\Desktop\PortableApps\Notepad++Portable\Notepad++Portable.exe"; proc.StartInfo.Arguments = String.Empty; proc.Start(); IntPtr appHwnd = proc.MainWindowHandle; while (appHwnd == IntPtr.Zero) { Thread.Sleep(100); appHwnd = proc.MainWindowHandle; } What's wrong? – Marcel Jan 04 '10 at 09:55
-
According to this (http://www.xtremedotnettalk.com/showpost.php?s=b115a21c0601804f80c9a2680db9c38f&p=461829&postcount=4) it may also be zero because an application does show a dialog or initializing flash first. – Marcel Jan 04 '10 at 10:23
6
This is not a recent topic but the answers are incomplete.
I agree with the Process.MainWindowHandle solution and to wait for the value but not with Sleep.
If you have just started a process and want to use its main window handle, consider using the WaitForInputIdle method to allow the process to finish starting, ensuring that the main window handle has been created.
This overload applies only to processes with a user interface and, therefore, a message loop.

Sam
- 91
- 1
- 5
-
-
i am sorry, for some reasons, this wait.... function throw the exception(there is only one), i will resolve with Sleep and Refresh – Sam May 16 '16 at 16:53
-
The `Process.WaitForInputIdle` seems to return almost immediately if it's used on a WPF application. I believe this is due to the WPF internals... – Grahamvs Jun 01 '18 at 14:07
-
It returns almost immediately for my .NET 4.5 application. Previous person said WPF, mine is just desktop application. – DAG Sep 09 '19 at 19:13
2
You could also call Refresh() on the process to be sure the info in accurate