How to get a specific explorer window handle after opening it in C# program

1,411 views
Skip to first unread message

Bert

unread,
Jun 5, 2009, 5:14:55 AM6/5/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
Hi All,
I want to open a Windows explorer folder in my C# program, then reset
the opened explorer window's position with SetWindowsPos via PInvoke.
I do it in following way:
Process p = Process.Start("explorer.exe", “C:\\”);
p.WaitForInputIdle();
IntPtr hWnd = p.MainWindowHandle;
SetWindowPos(hWnd,...)....(do it with PInvoke)
The problem is that when codes executes to "IntPtr hWnd =
p.MainWindowHandle;", the windows handle hWnd I got is IntPtr.Zero,
and the process p has exited already .
And I traced the process p's id, it seems that the id is not same with
the id of the system process "Explorer.exe" when I see it from Windows
"Task Manager", so the process created in my code is not same with the
process "Explorer.exe" in system. It seems that I could not get the
handle of the new opened explorer window in such way.
Then how could I get the handle of the new opened explorer window?
Maybe someone would say that you could use "FindWindow" API to get it,
but there maybe exist many explorer windows with the same folder
location, so in such way I could not judge which explorer window is
the one opened by my program.
Maybe others would say that you could use "GetForegroundWindow" API to
get the Foreground Window, yes I could get it in most of the time, but
sometimes the new opened explorer window does not appear foreground,
so it's not the right way also.
Anyone has other ideas?

Thanks.
Bert

Ralax

unread,
Jun 7, 2009, 2:20:15 AM6/7/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
Try the following code:

namespace ProcessHandle
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Get the process handle example.");
var process = new Process
{
StartInfo = new ProcessStartInfo
("explorer.exe", @"c:\")
};
process.Start();
Console.WriteLine("Process Id: " + process.Id);
Console.WriteLine("Process Name: " + process.ProcessName);
Console.WriteLine("Process Handle(IntPtr): " +
process.Handle.ToString());
Console.ReadLine();
}
}
}

use the above code, you can get the handle of the new opened window,
and then use win api set the position.

Bert

unread,
Jun 7, 2009, 9:17:05 PM6/7/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
Hi Ralax,

Thanks for your code.
What I need is the main window handle of the open explorer window
after I start the process, not the process id or process handle.

Any others has any solution?


Bert
Reply all
Reply to author
Forward
0 new messages