0
我无法使用以下代码获得存储的完整Excel文件文件路径,如"D:\test.xlsx"
,而以下代码对于其他文件类型(如docx,txt,ppt)可以正常工作。我想保存文件路径而不是可执行文件路径。使用ManagementObjectSearcher无法获取Excel保存的文件路径
[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();
}
}
有人可以让我知道在上面的代码中是否需要其他参数。