如何使用c#.net查找当前正在运行的应用程序? [英] How to find the Current Running Application using c#.net?
问题描述
大家好,
如何使用C#查找当前正在运行应用程序的应用程序?
场景:我正在开发C#WinForms应用程序......我找到了当前正在运行的进程名称..但我想显示当前正在运行的应用程序路径..请参阅下面的代码
Hello every one,
How can I find the application which is currently running application using C#?
Scenario: I m developing C# WinForms application...I found Current Running Process name..But I want to display current running application path..See this below code
public class SmallWork
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint ProcessId);
public static string GetActiveProcessFileName()
{
try
{
IntPtr hwnd = GetForegroundWindow();
uint pid;
GetWindowThreadProcessId(hwnd, out pid);
Process p = Process.GetProcessById((int)pid);
// return p.MainModule.FileName;
string CommandLine = GetMainModuleFilepath((int)pid);
var array = CommandLine.Split('"');
}
}
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 ((object)mo["CommandLine"]).ToString();
}
}
}
//Process testProcess = Process.GetProcessById(processId);
return null;
}
问题:如果我打开了三个MS-WORD文件,那么它只显示第一个打开的文件名..similarily MS-EXCEL和PDF页面..因为每个单词或Excel或Pdf只包含一个进程..但我想显示每个打开的文档或应用程序名称保存路径...我怎么能达到这个..
感谢大家提前给出答案和支持..
Problem: If I opened three MS-WORD files ,Then it display only First opened file name..similarily MS-EXCEL and PDF pages also..Because Every word or Excel or Pdf Contains Only One Process..But i want to shows Every Opened Document or application names saving with Path...How can i Achive this..
Thank you all for the answers and support in advance..
推荐答案
这对我有用: br />
添加对Microsoft.Office.Interop.Word的引用
然后添加以下内容:
This works for me:
Add a reference to Microsoft.Office.Interop.Word
Then add this usings:
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
最后,使用这种方法:
And finally, use this method:
private List<string> GetDocumentPaths()
{
List<string> Documents= new List<string>();
Word.Application wdapp;
wdapp = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
foreach (Document d in wdapp.Documents)
{
Documents.Add(Path.Combine(d.Path,d.Name));
}
return Documents;
}
这篇关于如何使用c#.net查找当前正在运行的应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!