I have developed a C# Windows application & created a exe of it.
What I want is that when ever I try to run the application, if it is already in running state, then activate that application instance, else start new application.
Th开发者_StackOverflowat means I don't want to open same application more than one time
Use the following code to set focus to the current application:
[DllImport("user32.dll")]
internal static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
...
Process currentProcess = Process.GetCurrentProcess();
IntPtr hWnd = currentProcess.MainWindowHandle;
if (hWnd != IntPtr.Zero)
{
SetForegroundWindow(hWnd);
ShowWindow(hWnd, User32.SW_MAXIMIZE);
}
You can PInvoke SetForegroundWindow() and SetFocus() from user32.dll to do this.
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
// SetFocus will just focus the keyboard on your application, but not bring your process to front.
// You don't need it here, SetForegroundWindow does the same.
// Just for documentation.
[DllImport("user32.dll")]
static extern IntPtr SetFocus(HandleRef hWnd);
As argument you pass the window handle of the process you want to bring in the front and focus.
SetForegroundWindow(myProcess.MainWindowHandle);
SetFocus(new HandleRef(null, myProcess.Handle)); // not needed
Also see the restrictions of the SetForegroundWindow Methode on msdna.
Use the following code part for multiple Instance checking of an exe, and if its true return at form load. For running this functionality in your app include using System.Diagnostics;
namespace
private bool CheckMultipleInstanceofApp()
{
bool check = false;
Process[] prc = null;
string ModName, ProcName;
ModName = Process.GetCurrentProcess().MainModule.ModuleName;
ProcName = System.IO.Path.GetFileNameWithoutExtension(ModName);
prc = Process.GetProcessesByName(ProcName);
if (prc.Length > 1)
{
MessageBox.Show("There is an Instance of this Application running");
check = true;
System.Environment.Exit(0);
}
return check;
}
Use Mutex to launch single instance of the application. Also, you can use Process class to find your application and SetFocus on it. Here http://social.msdn.microsoft.com/Forums/da-DK/csharpgeneral/thread/7fd8e358-9709-47f2-9aeb-6c35c7521dc3
精彩评论