2014-12-19 107 views
1

我想找到当前打开的文件的pah,该文件当前在Windows资源管理器中处于活动状态。我有文件夹的位置被点击该文件夹一段时间,但我们怎样才能像一个文本文件或字或类似的东西如何使用c查找最近打开/当前活动文件的鼠标指针的路径使用c#

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) 
      { 
       // this will get the folder location 
       string path = new Uri(xpl.LocationURL).LocalPath; 
       return ("location:" + xpl.LocationName + " path:" + path); 
      } 
      return "HWND" + handleint ; 
     } 

enter image description here

enter image description here

文件的路径

如你所见,但不是文本文件

+0

System.IO.Path是不够的? – LPs 2014-12-19 07:35:50

+1

“**当前打开的文件”是什么意思?请注意,在任何给定的时间,Windows及其中运行的程序都打开了*许多*文件。 – 2014-12-19 07:43:59

+0

当前打开的文件是活动的 – Vivekh 2014-12-19 07:48:47

回答

3
private 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“。

相关问题