Open explorer window and wait for it to close

早过忘川 提交于 2019-12-18 08:54:40

问题


I have a program that is opening an explorer window to a certain folder but i want to perform an action right after the explorer window is closed, but if I use the following code:

Process proc = Process.Start("explorer.exe", "D:\\");
proc.WaitForExit();

It is opening the explorer window as desired but the WaitForExit command has no effect and it just goes right past it.

Is there a different way of opening the explorer window that will be able to let me know when it is closed by the user?


回答1:


Cannot regenerate the error. Just tried this:

Process.Start("explorer.exe", "D:\\").WaitForExit();

and it blocks the current thread and waits until I close the explorer windows. Make sure that you're not executing the command on another thread than the one you want to block. Also make sure that you set every instance of a window to start a new instance of explorer.exe via importing below .reg file:

Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer]
"DesktopProcess"=dword:00000001
[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer]
"DesktopProcess"=dword:00000001
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\BrowseNewProcess]
"BrowseNewProcess"="Yes"
[HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\BrowseNewProcess]
"BrowseNewProcess"="Yes"

You'll need to restart your computer for this to take effect.




回答2:


The problem is explained pretty well at The Old New Thing:

The reason that WaitForSingleObject returns immediately is that Explorer is a single-instance program (well, limited-instance). When you open an Explorer window, the request is handed off to a running copy of Explorer, and the copy of Explorer you launched exits. That's why your WaitForSingleObject returns immediately.

He offers a couple solutions you could probably use (with some heavy use of PInvoke), like using something like this.

In the end it might just be easier for you to use some other type of file browser maybe from a C# library somewhere that you have more control over, rather than explorer.



来源:https://stackoverflow.com/questions/6156327/open-explorer-window-and-wait-for-it-to-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!