)
{
Process current = Process.GetCurrentProcess();
Process processes = Process.GetProcessesByName (current.ProcessName);
//查找相同名称的进程
foreach (Process process in processes)
{
//忽略当前进程
if (process.Id != current.Id)
{
//确认相同进程的程序运行位置是否一样.
if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
{
//Return the other process instance.
return process;
}
}
}
//No other instance was found, return null.
return null;
}
[VB.NET]
Public Shared Function RunningInstance() As Process
Dim current As Process = Process.GetCurrentProcess()
Dim processes As Process() = Process.GetProcessesByName(current.ProcessName)
''查找相同名的进程
Dim process As Process
For Each process In processes
''忽略当前进程
If process.Id <> current.Id Then
''确认相同名的进程运行位置是否相同
If [Assembly].GetExecutingAssembly().Location.Replace("/", "\") = current.MainModule.FileName Then
''返回其它的运行实例
Return process
End If
End If
Next process
''没有其它实例,返加空值
Return Nothing
End Function ''RunningInstance
示例
程序点击
下载(C#)
9、如何把所有的系统中正在运行的所有进程显示出来呢?
解答:用System.Diagnostics名字空间中的Process.GetProcess()静态成员
主要代码:
[C#]
Using System.Diagnostics;
foreach ( Process p in Process.GetProcesses() )
Console.WriteLine( p ); // string s = p.ToString();
[
vb.NET]
Imports System.Diagnostics
Dim p As Process
For Each p In Process.GetProcesses()
Console.WriteLine(p) '' string s = p.ToString()
Next p
示例
程序点击
下载(C#)
10、如何列出所有正在运行的应用程序呢?
解答:可有用EnumWindows 函数将枚举
计算机上的所有现有窗口,但我们用System.Diagnostics名字空间的静态函数Process.GetProcesses()可以避免EnumWindows的互操作性
问题。
主要代码:
[C#]
Using System.Diagnostics;
foreach ( Process p in Process.GetProcesses(System.Environment.MachineName) )
{
if( p.MainWindowHandle != IntPtr.Zero)
{
//显示用户程序名
Console.WriteLine( p ); // string s = p.ToString();
}
}
[
vb.NET]
Imports System.Diagnostics
Dim p As Process
For Each p In Process.GetProcesses(System.Environment.MachineName)
If p.MainWindowHandle <> IntPtr.Zero Then
''显示应用程序名
Console.WriteLine(p) '' string s = p.ToString();
End If
Next p