Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / February 2007

Tip: Looking for answers? Try searching our database.

Single Instance Form

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Mark Jerde - 22 Feb 2007 13:20 GMT
VS 2005.  When I google "CSharp single instance form" the returned pages
usually use a Mutex or the VB.NET runtime library.
  http://en.csharp-online.net/Application_Architecture_in_Windows_Forms_2.0%E2%80%
94Single-Instance_Detection_and_Management

  http://www.codeproject.com/csharp/SingleInstanceApplication.asp
  http://blogs.msdn.com/onoj/archive/2004/06/04/148532.aspx

"Program.cs" below seems to work fine.  A feature is it restores a minimized
form.  Is this code ok or is there a "gotcha"?  I'm aware it's probably
slower than a Mutex but restoring the minimized form is nice.

Thanks.

  -- Mark

========== Program.cs =========

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;

namespace OneInstance {
   internal static class Program {
       /// <summary>
       /// The main entry point for the application.
       /// </summary>
       ///
       ///
       [STAThread]
       public static void Main() {
           //Get the running instance.
           Process instance = RunningInstance();

           if (instance == null) {
               //If no other instance of program is running, show form
               Application.Run(new Form());
           } else {
               //There is another instance of this process, do not allow
second
               HandleRunningInstance(instance);
               MessageBox.Show("Program already running! \n Focus
returned", "Already Open",
                               MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
           }
       }

       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
               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 process;
               }
           }
           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;
   }
}
PokerMan - 22 Feb 2007 13:25 GMT
Why not use a singleton pattern, its specifically for single instance only
classes.

> VS 2005.  When I google "CSharp single instance form" the returned pages
> usually use a Mutex or the VB.NET runtime library.
[quoted text clipped - 84 lines]
>    }
> }
Mark Jerde - 22 Feb 2007 13:44 GMT
This was a project written by a college student who works for us part time.
I wanted the MS Outlook feature of restoring a minimized form.  This is his
solution and I'm just wondering if anyone sees something that won't work all
the time.

  -- Mark

> Why not use a singleton pattern, its specifically for single instance only
> classes.
[quoted text clipped - 87 lines]
>>    }
>> }
Jon Skeet [C# MVP] - 22 Feb 2007 21:54 GMT
> Why not use a singleton pattern, its specifically for single instance only
> classes.

Singletons work within a process - the OP wants to ensure that when a
second process starts, it restores the first process's window. The
singleton pattern can't help with that at all.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.