12

Is there a way to get the window handle (IntPtr) for a window after its launched from a C# app with Process.Start()?

1
  • Process p = Process.Start("Notepad"); p.WaitForInputIdle(); SetParent(p.MainWindowHandle, CBox.Handle); Commented Mar 28, 2021 at 0:24

4 Answers 4

28

If it's the main window you're after, Process.MainWindowHandle will give you what you need.

Sign up to request clarification or add additional context in comments.

Comments

9

Use

process.MainWindowHandle;

It probably is 0 when launching the app, so you might want to loop and sleep until it is filled up.

2 Comments

Hi 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?
According to this (xtremedotnettalk.com/…) it may also be zero because an application does show a dialog or initializing flash first.
7

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.

Process.WaitForInputIdle

This overload applies only to processes with a user interface and, therefore, a message loop.

4 Comments

I think this should actually be a comment.
i am sorry, for some reasons, this wait.... function throw the exception(there is only one), i will resolve with Sleep and Refresh
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...
It returns almost immediately for my .NET 4.5 application. Previous person said WPF, mine is just desktop application.
3

You could also call Refresh() on the process to be sure the info in accurate

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.