Get path of current active window using window han

2020-07-18 05:23发布

I'd like to know how to grab the Path of the current active window using C#.

i get handle of currnet active window

        const int nChars = 256;
        int handle = 0;
        StringBuilder Buff = new StringBuilder(nChars);

        handle = GetForegroundWindow(); 

now how do i get path of this window?

i.e: Path of "my document" window is

C:\Users\User\Documents

-=-=-==-=-=edit-=-=-=-=-=-
i want to wirte program to monitor "windows explorer" and see Where the user goes?
(i.e:user go to c:\ and then go to program files and then go to Internet Explorer and i want to get this path:C:\Program Files\Internet Explorer. enter image description here

标签: c# winapi
2条回答
Root(大扎)
2楼-- · 2020-07-18 05:44

use a thread...

                Exception threadEccezione = null;

                System.Threading.Thread staThread = new System.Threading.Thread(
                        delegate()
                        {
                            try
                            {
                                //SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();
                                var explorer = new SHDocVw.ShellWindowsClass().Cast<SHDocVw.InternetExplorer>().Where(hwnd => hwnd.HWND == handle).FirstOrDefault();

                                if (explorer != null)
                                {
                                    string path = new Uri(explorer.LocationURL).LocalPath;
                                    MessageBox.Show(path);
                                }
                            }
                            catch (Exception ex)
                            {
                                threadEccezione = ex;
                            }
                        }
                    );
                ;
                staThread.Start();
                staThread.Join();
查看更多
▲ chillily
3楼-- · 2020-07-18 05:47

Add a reference (COM) to "Microsoft Internet Controls"

var explorer = new SHDocVw.ShellWindowsClass().Cast<SHDocVw.InternetExplorer>().Where(hwnd => hwnd.HWND == handle).FirstOrDefault();
if (explorer != null) {
    string path = new Uri(explorer.LocationURL).LocalPath;
    Console.WriteLine("name={0}, path={1}", explorer.LocationName, path);
}

Prints the title/path of the explorer.exe instance with the main window handle in handle.

查看更多
登录 后发表回答