简体   繁体   English

使用窗口句柄获取当前活动窗口的路径

[英]Get path of current active window using window handle

I'd like to know how to grab the Path of the current active window using C#. 我想知道如何使用C#获取当前活动窗口的路径。

i get handle of currnet active window 我得到currnet活动窗口的句柄

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

        handle = GetForegroundWindow(); 

now how do i get path of this window? 现在我如何获得该窗口的路径?

ie: 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? 我想编写监视“ Windows资源管理器”的程序,并查看用户的位置?
(ie: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. (即:用户转到c:\\,然后转到程序文件,然后转到Internet Explorer,我想获取此路径:C:\\ Program Files \\ Internet Explorer。 在此处输入图片说明

Add a reference (COM) to "Microsoft Internet Controls" 将引用(COM)添加到“ Microsoft Internet控件”

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 . 打印出带有主窗口句柄在handle中的explorer.exe实例的标题/路径。

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM