我无法使用以下代码存储完整的Excel文件路径,如"D:\test.xlsx"
,而以下代码适用于其他文件类型,如docx,txt,ppt。我想保存文件路径而不是可执行路径。
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
private void timer1_Tick(object sender, EventArgs e)
{
string psFilename = ActiveFileName();
MessageBox.Show(psFilename);
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 20 * 1000;
timer1.Start();
}
private static string ActiveFileName()
{
try
{
IntPtr hWnd = GetForegroundWindow();
uint procId = 0;
GetWindowThreadProcessId(hWnd, out procId);
//var proc = System.Diagnostics.Process.GetProcessById((int)procId);
//if (proc != null)
//{
// if (proc.Modules[0] != null)
// {
return (GetMainModuleFilepath((int)(procId)));
// }
//}
}
catch (Exception ex)
{
return ex.Message.ToString() + " first";
}
return string.Empty;
}
public static string GetMainModuleFilepath(int processId)
{
try
{
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"];
}
}
}
System.Diagnostics.Process testProcess = System.Diagnostics.Process.GetProcessById(processId);
return null;
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
如果上述代码中需要任何其他参数,有人可以告诉我。
答案 0 :(得分:0)
我能够解决我没有获得excel保存文件路径的问题。我已使用handle.exe以下代码,我能够获取文件路径。
private static string GetExcelFileName(string pid)
{
string actualPath = string.Empty;
try
{
Process tool = new Process();
tool.StartInfo.FileName = @"C:\PrinterPlusPlus\handle.exe";
tool.StartInfo.Arguments = "/accepteula -p " + pid;
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.StartInfo.CreateNoWindow = true;
tool.Start();
string outputTool = tool.StandardOutput.ReadToEnd();
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = outputTool.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in lines)
{
if (s.Contains(".xlsx") && !s.Contains("$"))
{
string[] arrPath = s.Split(new string[] { "File" }, StringSplitOptions.None);
string path = string.Empty;
if (arrPath.Length > 1)
{
actualPath = arrPath[1].Trim();
}
}
}
}
catch
{
}
return actualPath;
}