If your want to ensure that only a single instance of your application may be executed at any given time, then use a Mutex object,
which can be shared across-process boundaries as a singleton:
private static Mutex SingleInstanceMutex;
/// <summary>Disposes the mutex object that ensures only a single instance of this application will execute at any given
time.</summary>
private static void SingleInstanceProcess_Exited(object sender, EventArgs e)
{
if (SingleInstanceMutex != null)
SingleInstanceMutex.Close();
}
public static void Main()
{
Process process = Process.GetCurrentProcess();
bool createdNew;
SingleInstanceMutex = new Mutex(true, process.ProcessName, out createdNew);
if (createdNew)
process.Exited+= new EventHandler(SingleInstanceProcess_Exited);
else
// Allow only a single instance of the app to execute
process.Kill();
}
So if a window is hidden, it seems not to have a windowhandle.
Incorrect. I attempted to reproduce the behavior your experiencing and I've done so with success. Take this code for example:
CheckHiddenHandleForm form = new CheckHiddenHandleForm();
Console.WriteLine("Show Form...");
form.Show();
System.Windows.Forms.Application.DoEvents();
Console.WriteLine("\tMainWindowHandle: {0}", Process.GetCurrentProcess().MainWindowHandle);
Console.WriteLine("\tForm.Handle: {0}", form.Handle);
Console.WriteLine("Hide Form...");
form.Hide();
System.Windows.Forms.Application.DoEvents();
Console.WriteLine("\tMainWindowHandle: {0}", Process.GetCurrentProcess().MainWindowHandle);
Console.WriteLine("\tForm.Handle: {0}", form.Handle);
Console.WriteLine("Close Form...");
form.Close();
System.Windows.Forms.Application.DoEvents();
Console.WriteLine("\tMainWindowHandle: {0}", Process.GetCurrentProcess().MainWindowHandle);
Outputs the following results to the Console window:
Show Form...
MainWindowHandle: 5308896 -- MainWindowHandle
Form.Handle: 5308896 -- Notice that the Form.Handle is the MainWindowHandle
Hide Form...
MainWindowHandle: 0 -- there is no longer a Main window for the process since the Form has been hidden
Form.Handle: 5308896 -- *** The window still has a handle ***
Close Form...
MainWindowHandle: 0 -- The window is now disposed (Form.Handle is now inaccessible and assumed
IntPtr.Zero)
Press any key to continue
As you can see, the window still has a handle, however, once it is hidden it is no longer the "MainWindow" of the process. You may
have to use Windows API calls to obtain the handle to the window, or just ignore it because it's hidden. That's what you're
attempting to accomplish anyway, correct?
I suggest looping through all of the processes with the same name if you do not want to ensure a single instance of the app using
the Mutex in my code example above. If the process Id is not of the current process, AND the MainWindowHandle is not IntPtr.Zero
then use my Interop code I supplied to you in a previous post to show the window.
GL