[c#]
public static process runninginstance()
{
process current = process.getcurrentprocess();
process[] processes = process.getprocessesbyname (current.processname);
//loop through the running processes in with the same name
foreach (process process in processes)
{
//ignore the current process
if (process.id != current.id)
{
//make sure that the process is running from the exe file.
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)
loop through the running processes in with the same name
dim process as process
for each process in processes
ignore the current process
if process.id <> current.id then
make sure that the process is running from the exe file.
if [assembly].getexecutingassembly().location.replace("/", "\") = current.mainmodule.filename then
return the other process instance.
return process
end if
end if
next process
no other instance was found, return null.
return nothing
end function runninginstance
如果检测到已有窗体实例,将此实例显示出来参考:
[stathread]
static void main()
{
//get the running instance.
process instance = runninginstance();
if (instance == null)
{
//there isnt another instance, show our form.
application.run (new form2());
}
else
{
//there is another instance of this process.
handlerunninginstance(instance);
}
}
public static process runninginstance()
{
process current = process.getcurrentprocess();
process[] processes = process.getprocessesbyname (current.processname);
//loop through the running processes in with the same name
foreach (process process in processes)
{
//ignore the current process
if (process.id != current.id)
{
//make sure that the process is running from the exe file.
if (assembly.getexecutingassembly().location.replace("/", "\\") ==current.mainmodule.filename)
{
//return the other process instance.
return process;
}
}
}
//no other instance was found, return null.
return null;
}
public static void handlerunninginstance(process instance)
{
//make sure the window is not minimized or maximized
showwindowasync (instance.mainwindowhandle , ws_shownormal);
//set the real intance to foreground window
setforegroundwindow (instance.mainwindowhandle);
}
[dllimport("user32.dll")]
private static extern bool showwindowasync( intptr hwnd, int cmdshow);
[dllimport("user32.dll")]
private static extern bool setforegroundwindow(intptr hwnd);
private const int ws_shownormal = 1