【问题标题】:How to get a active file/Application Complete path with file Extension如何使用文件扩展名获取活动文件/应用程序完整路径
【发布时间】:2014-12-17 14:13:33
【问题描述】:

我正在尝试使用 Windows 应用程序 (c#) 在我的系统上跟踪活动的应用程序/文件。

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        private string GetActiveWindowTitle()
        {
            const int nChars = 256;
            StringBuilder Buff = new StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString() + " " + handle;
            }
            return null;
        }


        private string GetActiveWindowPath()
        {
            const int nChars = 256;
            StringBuilder Buff = new StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();
            int handleint = int.Parse(handle + "");
            SHDocVw.ShellWindows explorer = new SHDocVw.ShellWindows();

            //var xy = new SHDocVw.InternetExplorerMedium();

            var xpl = explorer.Cast<SHDocVw.InternetExplorerMedium>().Where(hwnd => hwnd.HWND == handleint).FirstOrDefault();
            if (xpl != null)
            {
                string path = new Uri(xpl.LocationURL).LocalPath;
                return ("location:" + xpl.LocationName + " path:" + path);
            }
            return "HWND" + handleint;
        }

但是通过使用上面的代码我只得到文件标题而不是带有扩展名的完整文件名,通过使用其他方法我只是得到文件夹信息。

但我正在尝试获取带有路径的文件扩展名 例如:D:\New Folder\sampleFile.txt

【问题讨论】:

    标签: c# directory winapp


    【解决方案1】:
     public static string GetMainModuleFilepath(int processId)
        {
            string wmiQueryString = "SELECT * FROM Win32_Process WHERE ProcessId = " + processId;
            using (var searcher = new ManagementObjectSearcher(wmiQueryString))
            {
                using (var results = searcher.Get())
                {
                    ManagementObject mo = results.Cast<ManagementObject>().FirstOrDefault();
                    if (mo != null)
                    {
                        return (string)mo["CommandLine"];
                    }
                }
            }
            Process testProcess = Process.GetProcessById(processId);
            return null;
        }
    

    通过使用这个函数,你会得到一个类似的字符串

    "c:..\notepade.exe" D:\New Folder\sampleFile.txt"

    在拆分之后,您希望获得路径。 我已经为office 2007编写了这段代码,你们可以调试并找到更高版本的正确路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 2010-11-27
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      相关资源
      最近更新 更多