我正在Windows Server 2012 R2上运行代码,在那里我有多个会话。
在每个会话中,很少打开具有不同窗口名称的Notepad.exe。
我如何从所有会话中获取所有Notepad.exe进程的列表,以便可以从列表中最小化所选进程的窗口或关闭进程?
我使用了这段代码,但是它只给我当前登录会话中的进程。
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (!string.IsNullOrEmpty(process.MainWindowTitle))
{
if (process.ProcessName == "notepad")
{
Console.WriteLine("Process: {0} - ID: {1} - Window title: {2}", process.ProcessName, process.Id, process.MainWindowTitle);
}
}
}
答案 0 :(得分:0)
感谢@Lex Li(来自nuget的二手图书馆),我解决了我的问题。
我使用这一行if (process.ProcessName == "notepad.exe" && session.SessionId == process.SessionId)
仅提取我需要的进程名称,并将其与会话匹配。
using Cassia;
// call all process from sessions
private void GetSessionsProcess()
{
ITerminalServicesManager manager = new TerminalServicesManager();
ITerminalServer server = manager.GetLocalServer(); // server name
server.Open();
WriteProcesses(server.GetProcesses(), manager);
}
// get all process that is running in all sessions
private void WriteProcesses(IEnumerable<ITerminalServicesProcess> processes, ITerminalServicesManager manager)
{
ITerminalServer server = manager.GetLocalServer();
foreach (ITerminalServicesProcess process in processes)
{
foreach (ITerminalServicesSession session in server.GetSessions())
{
if (process.ProcessName == "notepad.exe" && session.SessionId == process.SessionId)
{
PopulateTerminalsList(process.SessionId.ToString(), process.ProcessId.ToString(), process.ProcessName, session.UserAccount.ToString(), session.UserName);
}
}
}
}