How to limit program can only run one instance.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Boki Digtal

    How to limit program can only run one instance.

    Hi All,

    How to limit the c# program can only run one instance at the same
    time ?

    Thank you!

    Best regards,
    Boki.

  • Mark Rae [MVP]

    #2
    Re: How to limit program can only run one instance.

    "Boki Digtal" <bokiteam@ms21. hinet.netwrote in message news:1185184038 .720113.13850@x 35g2000prf.goog legroups.com...
    How to limit the c# program can only run one instance at the same
    time ?

    using System.Threadin g;

    bool blnFirstInstanc e;

    using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out blnFirstInstanc e))
    {
    if (!blnFirstInsta nce)
    {
    MessageBox.Show ("<app nameis already running", "Single Use Only", MessageBoxButto ns.OK, MessageBoxIcon. Stop);
    Application.Exi t();
    }
    else
    {
    Application.Run (new Form1()); // or whatever your startup is...
    }
    }


    --
    Mark Rae
    ASP.NET MVP

    Comment

    • Boki Digtal

      #3
      Re: How to limit program can only run one instance.

      On 7 23 , 6 11 , "Mark Rae [MVP]" <m...@markNOSPA Mrae.netwrote:
      "Boki Digtal" <bokit...@ms21. hinet.netwrote in messagenews:118 5184038.720113. 13850@x35g2000p rf.googlegroups .com...
      How to limit the c# program can only run one instance at the same
      time ?
      >
      using System.Threadin g;
      >
      bool blnFirstInstanc e;
      >
      using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out blnFirstInstanc e))
      {
      if (!blnFirstInsta nce)
      {
      MessageBox.Show ("<app nameis already running", "Single Use Only", MessageBoxButto ns.OK, MessageBoxIcon. Stop);
      Application.Exi t();
      }
      else
      {
      Application.Run (new Form1()); // or whatever your startup is...
      }
      >
      }
      >
      --
      Mark Rae
      ASP.NET MVPhttp://www.markrae.net
      Great, thanks!

      Boki.

      Comment

      • Boki Digtal

        #4
        Re: How to limit program can only run one instance.

        On 7 24 , 2 27 , Boki Digtal <bokit...@ms21. hinet.netwrote:
        On 7 23 , 6 11 , "Mark Rae [MVP]" <m...@markNOSPA Mrae.netwrote:
        >
        >
        >
        "Boki Digtal" <bokit...@ms21. hinet.netwrote in messagenews:118 5184038.720113. 13850@x35g2000p rf.googlegroups .com...
        How to limit the c# program can only run one instance at the same
        time ?
        >
        using System.Threadin g;
        >
        bool blnFirstInstanc e;
        >
        using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out blnFirstInstanc e))
        {
        if (!blnFirstInsta nce)
        {
        MessageBox.Show ("<app nameis already running", "Single Use Only", MessageBoxButto ns.OK, MessageBoxIcon. Stop);
        Application.Exi t();
        }
        else
        {
        Application.Run (new Form1()); // or whatever your startup is...
        }
        >
        }
        >
        --
        Mark Rae
        ASP.NET MVPhttp://www.markrae.net
        >
        Great, thanks!
        >
        Boki.
        Is there any easier way like OnlyOneInstance = ture;

        Thanks :)

        Boki.

        Comment

        • Mark Rae [MVP]

          #5
          Re: How to limit program can only run one instance.

          "Boki Digtal" <bokiteam@ms21. hinet.netwrote in message
          news:1185758482 .386552.83280@i 38g2000prf.goog legroups.com...
          using System.Threadin g;
          >>
          bool blnFirstInstanc e;
          >>
          using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out
          blnFirstInstanc e))
          {
          if (!blnFirstInsta nce)
          {
          MessageBox.Show ("<app nameis already running", "Single Use
          Only", MessageBoxButto ns.OK, MessageBoxIcon. Stop);
          Application.Exi t();
          }
          else
          {
          Application.Run (new Form1()); // or whatever your startup
          is...
          }
          }
          >>
          >Great, thanks!
          >
          Is there any easier way like OnlyOneInstance = ture;
          An easier way? The above is only a dozen lines of code...

          Can't you get it to work, then...?


          --
          Mark Rae
          ASP.NET MVP


          Comment

          • Boki Digtal

            #6
            Re: How to limit program can only run one instance.

            On 7 30 , 1 51 , "Mark Rae [MVP]" <m...@markNOSPA Mrae.netwrote:
            "Boki Digtal" <bokit...@ms21. hinet.netwrote in message
            >
            news:1185758482 .386552.83280@i 38g2000prf.goog legroups.com...
            >
            >
            >
            using System.Threadin g;
            >
            bool blnFirstInstanc e;
            >
            using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out
            blnFirstInstanc e))
            {
            if (!blnFirstInsta nce)
            {
            MessageBox.Show ("<app nameis already running", "Single Use
            Only", MessageBoxButto ns.OK, MessageBoxIcon. Stop);
            Application.Exi t();
            }
            else
            {
            Application.Run (new Form1()); // or whatever your startup
            is...
            }
            }
            >
            Great, thanks!
            >
            Is there any easier way like OnlyOneInstance = ture;
            >
            An easier way? The above is only a dozen lines of code...
            >
            Can't you get it to work, then...?
            >
            --
            Mark Rae
            ASP.NET MVPhttp://www.markrae.net
            Sorry, in fact, I don't have try it yet.

            If I recall correctly, there is a setting in VC6, when we assign so
            many parameters to create a form. For this purpose, what we need to do
            is assign a parameter as true only.

            I believe your code can work, but I am just curious if there is any
            other methods.

            :)

            Thanks!

            Best regards,
            Boki.



            Comment

            • Jon Skeet [C# MVP]

              #7
              Re: How to limit program can only run one instance.

              On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21. hinet.netwrote:
              Sorry, in fact, I don't have try it yet.
              >
              If I recall correctly, there is a setting in VC6, when we assign so
              many parameters to create a form. For this purpose, what we need to do
              is assign a parameter as true only.
              >
              I believe your code can work, but I am just curious if there is any
              other methods.
              You could add a reference to the Microsoft.Visua lBasic assembly and
              use the WindowsFormsApp licationBase class which I believe has this
              sort of functionality. I don't know much about it, but it *might* make
              things easier for you.

              Jon

              Comment

              • Boki Digtal

                #8
                Re: How to limit program can only run one instance.

                On 7 30 , 3 26 , "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
                On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21. hinet.netwrote:
                >
                Sorry, in fact, I don't have try it yet.
                >
                If I recall correctly, there is a setting in VC6, when we assign so
                many parameters to create a form. For this purpose, what we need to do
                is assign a parameter as true only.
                >
                I believe your code can work, but I am just curious if there is any
                other methods.
                >
                You could add a reference to the Microsoft.Visua lBasic assembly and
                use the WindowsFormsApp licationBase class which I believe has this
                sort of functionality. I don't know much about it, but it *might* make
                things easier for you.
                >
                Jon
                visual basic ... ? but I am using c# ...

                Boki.

                Comment

                • Mark Rae [MVP]

                  #9
                  Re: How to limit program can only run one instance.

                  "Boki Digtal" <bokiteam@ms21. hinet.netwrote in message
                  news:1185781978 .832708.291660@ j4g2000prf.goog legroups.com...
                  On 7 30 , 3 26 , "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
                  >On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21. hinet.netwrote:
                  >>
                  Sorry, in fact, I don't have try it yet.
                  >>
                  If I recall correctly, there is a setting in VC6, when we assign so
                  many parameters to create a form. For this purpose, what we need to do
                  is assign a parameter as true only.
                  >>
                  I believe your code can work, but I am just curious if there is any
                  other methods.
                  >>
                  >You could add a reference to the Microsoft.Visua lBasic assembly and
                  >use the WindowsFormsApp licationBase class which I believe has this
                  >sort of functionality. I don't know much about it, but it *might* make
                  >things easier for you.
                  >>
                  >Jon
                  >
                  visual basic ... ? but I am using c# ...
                  Yes, but you can set a reference to the Microsoft.Visua lBasic assembly and
                  use the (without wishing to get into a language war) "hand-holding"
                  functions ported over from VB6 if the code I suggested (which I pretty much
                  nicked from Jon anyway) is too much for you...


                  --
                  Mark Rae
                  ASP.NET MVP


                  Comment

                  • Boki Digtal

                    #10
                    Re: How to limit program can only run one instance.

                    On 7 30 , 4 18 , "Mark Rae [MVP]" <m...@markNOSPA Mrae.netwrote:
                    "Boki Digtal" <bokit...@ms21. hinet.netwrote in message
                    >
                    news:1185781978 .832708.291660@ j4g2000prf.goog legroups.com...
                    >
                    >
                    >
                    On 7 30 , 3 26 , "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
                    On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21. hinet.netwrote:
                    >
                    Sorry, in fact, I don't have try it yet.
                    >
                    If I recall correctly, there is a setting in VC6, when we assign so
                    many parameters to create a form. For this purpose, what we need to do
                    is assign a parameter as true only.
                    >
                    I believe your code can work, but I am just curious if there is any
                    other methods.
                    >
                    You could add a reference to the Microsoft.Visua lBasic assembly and
                    use the WindowsFormsApp licationBase class which I believe has this
                    sort of functionality. I don't know much about it, but it *might* make
                    things easier for you.
                    >
                    Jon
                    >
                    visual basic ... ? but I am using c# ...
                    >
                    Yes, but you can set a reference to the Microsoft.Visua lBasic assembly and
                    use the (without wishing to get into a language war) "hand-holding"
                    functions ported over from VB6 if the code I suggested (which I pretty much
                    nicked from Jon anyway) is too much for you...
                    >
                    --
                    Mark Rae
                    ASP.NET MVPhttp://www.markrae.net
                    OK, got it, thanks :)

                    Boki.

                    Comment

                    • Ivica Muruzovic

                      #11
                      Re: How to limit program can only run one instance.

                      Try this

                      using System;
                      using System.Windows. Forms;
                      using System.Runtime. InteropServices ;
                      using System.Text;
                      using System.Diagnost ics;
                      using System.Threadin g;
                      using System.Reflecti on;
                      using System.IO;

                      namespace SingleInstance
                      {
                      /// <summary>
                      /// Summary description for SingleApp.
                      /// </summary>
                      public class SingleApplicati on
                      {
                      public SingleApplicati on()
                      {

                      }
                      /// <summary>
                      /// Imports
                      /// </summary>

                      [DllImport("user 32.dll")]
                      private static extern int ShowWindow(IntP tr hWnd, int
                      nCmdShow);

                      [DllImport("user 32.dll")]
                      private static extern int SetForegroundWi ndow(IntPtr
                      hWnd);

                      [DllImport("user 32.dll")]
                      private static extern int IsIconic(IntPtr hWnd);

                      /// <summary>
                      /// GetCurrentInsta nceWindowHandle
                      /// </summary>
                      /// <returns></returns>
                      private static IntPtr GetCurrentInsta nceWindowHandle ()
                      {
                      IntPtr hWnd = IntPtr.Zero;
                      Process process = Process.GetCurr entProcess();
                      Process[] processes =
                      Process.GetProc essesByName(pro cess.ProcessNam e);
                      foreach(Process _process in processes)
                      {
                      // Get the first instance that is not
                      this instance, has the
                      // same process name and was started
                      from the same file name
                      // and location. Also check that the
                      process has a valid
                      // window handle in this session to
                      filter out other user's
                      // processes.
                      if (_process.Id != process.Id &&
                      _process.MainMo dule.FileName
                      == process.MainMod ule.FileName &&
                      _process.MainWi ndowHandle !=
                      IntPtr.Zero)
                      {
                      hWnd =
                      _process.MainWi ndowHandle;
                      break;
                      }
                      }
                      return hWnd;
                      }
                      /// <summary>
                      /// SwitchToCurrent Instance
                      /// </summary>
                      private static void SwitchToCurrent Instance()
                      {
                      IntPtr hWnd =
                      GetCurrentInsta nceWindowHandle ();
                      if (hWnd != IntPtr.Zero)
                      {
                      // Restore window if minimised. Do not
                      restore if already in
                      // normal or maximised window state,
                      since we don't want to
                      // change the current state of the
                      window.
                      if (IsIconic(hWnd) != 0)
                      {
                      ShowWindow(hWnd , SW_RESTORE);
                      }

                      // Set foreground window.
                      SetForegroundWi ndow(hWnd);
                      }
                      }

                      /// <summary>
                      /// Execute a form base application if another
                      instance already running on
                      /// the system activate previous one
                      /// </summary>
                      /// <param name="frmMain"> main form</param>
                      /// <returns>true if no previous instance is
                      running</returns>
                      public static bool Run(System.Wind ows.Forms.Form
                      frmMain)
                      {
                      if(IsAlreadyRun ning())
                      {
                      //set focus on previously running app
                      SwitchToCurrent Instance();
                      return false;
                      }
                      Application.Run (frmMain);
                      return true;
                      }

                      /// <summary>
                      /// for console base application
                      /// </summary>
                      /// <returns></returns>
                      public static bool Run()
                      {
                      if(IsAlreadyRun ning())
                      {
                      return false;
                      }
                      return true;
                      }

                      /// <summary>
                      /// check if given exe alread running or not
                      /// </summary>
                      /// <returns>return s true if already running</returns>
                      private static bool IsAlreadyRunnin g()
                      {
                      string strLoc =
                      Assembly.GetExe cutingAssembly( ).Location;
                      FileSystemInfo fileInfo = new
                      FileInfo(strLoc );
                      string sExeName = fileInfo.Name;
                      bool bCreatedNew;

                      mutex = new Mutex(true, "Global\\"+sExe Name,
                      out bCreatedNew);
                      if (bCreatedNew)
                      mutex.ReleaseMu tex();

                      return !bCreatedNew;
                      }

                      static Mutex mutex;
                      const int SW_RESTORE = 9;
                      }
                      }

                      IN PROGRAM.CS add line
                      SingleApplicati on.Run(new frmMain());


                      On Mon, 30 Jul 2007 01:29:28 -0700, Boki Digtal
                      <bokiteam@ms21. hinet.netwrote:
                      >On 7 30 , 4 18 , "Mark Rae [MVP]" <m...@markNOSPA Mrae.netwrote:
                      >"Boki Digtal" <bokit...@ms21. hinet.netwrote in message
                      >>
                      >news:118578197 8.832708.291660 @j4g2000prf.goo glegroups.com.. .
                      >>
                      >>
                      >>
                      On 7 30 , 3 26 , "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
                      >On Jul 30, 8:15 am, Boki Digtal <bokit...@ms21. hinet.netwrote:
                      >>
                      Sorry, in fact, I don't have try it yet.
                      >>
                      If I recall correctly, there is a setting in VC6, when we assign so
                      many parameters to create a form. For this purpose, what we need to do
                      is assign a parameter as true only.
                      >>
                      I believe your code can work, but I am just curious if there is any
                      other methods.
                      >>
                      >You could add a reference to the Microsoft.Visua lBasic assembly and
                      >use the WindowsFormsApp licationBase class which I believe has this
                      >sort of functionality. I don't know much about it, but it *might* make
                      >things easier for you.
                      >>
                      >Jon
                      >>
                      visual basic ... ? but I am using c# ...
                      >>
                      >Yes, but you can set a reference to the Microsoft.Visua lBasic assembly and
                      >use the (without wishing to get into a language war) "hand-holding"
                      >functions ported over from VB6 if the code I suggested (which I pretty much
                      >nicked from Jon anyway) is too much for you...
                      >>
                      >--
                      >Mark Rae
                      >ASP.NET MVPhttp://www.markrae.net
                      >
                      >OK, got it, thanks :)
                      >
                      >Boki.

                      Comment

                      • Mark Rae [MVP]

                        #12
                        Re: How to limit program can only run one instance.

                        "Ivica Muruzovic" <kvin@eunet.yuw rote in message
                        news:aikta3li95 78vr8f2s2elrra4 3g1h100v0@4ax.c om...
                        using System.Runtime. InteropServices ;
                        [DllImport("user 32.dll")]
                        There really is no need to use WinAPI for this...


                        --
                        Mark Rae
                        ASP.NET MVP


                        Comment

                        • Boki

                          #13
                          Re: How to limit program can only run one instance.

                          On 7 23 , 6 11 , "Mark Rae [MVP]" <m...@markNOSPA Mrae.netwrote:
                          "Boki Digtal" <bokit...@ms21. hinet.netwrote in messagenews:118 5184038.720113. 13850@x35g2000p rf.googlegroups .com...
                          How to limit the c# program can only run one instance at the same
                          time ?
                          >
                          using System.Threadin g;
                          >
                          bool blnFirstInstanc e;
                          >
                          using (Mutex objMutex = new Mutex(false, "Local\\" + "<app name>", out blnFirstInstanc e))
                          {
                          if (!blnFirstInsta nce)
                          {
                          MessageBox.Show ("<app nameis already running", "Single Use Only", MessageBoxButto ns.OK, MessageBoxIcon. Stop);
                          Application.Exi t();
                          }
                          else
                          {
                          Application.Run (new Form1()); // or whatever your startup is...
                          }
                          >
                          }
                          >
                          --
                          Mark Rae
                          ASP.NET MVPhttp://www.markrae.net
                          Hi,
                          Please see my complete "Program.cs " below:
                          After I did this, it can still run more than one instance.

                          /////////////////////////////////////////////////
                          using System;
                          using System.Collecti ons.Generic;
                          using System.Windows. Forms;
                          using System.Threadin g;

                          namespace Ring_Buffer_Tes t
                          {

                          static class Program
                          {
                          /// <summary>
                          /// The main entry point for the application.
                          /// </summary>
                          [STAThread]
                          static void Main()
                          {

                          bool blnFirstInstanc e;
                          using (Mutex objMutex = new Mutex(false,"Lo cal\\" +
                          "BokiTestin g", out blnFirstInstanc e))

                          Application.Ena bleVisualStyles ();
                          Application.Set CompatibleTextR enderingDefault (false);


                          if (!blnFirstInsta nce)
                          {
                          MessageBox.Show ("<app nameis already running", "Single
                          Use Only", MessageBoxButto ns.OK, MessageBoxIcon. Stop);
                          Application.Exi t();
                          }
                          else
                          {
                          Application.Run (new Form1());
                          }

                          }
                          }
                          }
                          ////////////////


                          I don't know why ...

                          Boki.

                          Comment

                          • Jon Skeet [C# MVP]

                            #14
                            Re: How to limit program can only run one instance.

                            Boki <boki.digital@g mail.comwrote:
                            Please see my complete "Program.cs " below:
                            After I did this, it can still run more than one instance.
                            Yes, because your "using" statement for the mutex doesn't have braces
                            round the code. You've effectively got:

                            bool blnFirstInstanc e;

                            using (Mutex objMutex = new Mutex(false,"Lo cal\\" + "BokiTestin g",
                            out blnFirstInstanc e))
                            {
                            Application.Ena bleVisualStyles ();
                            }

                            Application.Set CompatibleTextR enderingDefault (false);

                            // Rest of code...

                            The idea is to hold the mutex for the whole of the time your app is
                            running.

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

                            Comment

                            • Boki

                              #15
                              Re: How to limit program can only run one instance.

                              On 8 2 , 2 22 , Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
                              Boki <boki.digi...@g mail.comwrote:
                              Please see my complete "Program.cs " below:
                              After I did this, it can still run more than one instance.
                              >
                              Yes, because your "using" statement for the mutex doesn't have braces
                              round the code. You've effectively got:
                              >
                              bool blnFirstInstanc e;
                              >
                              using (Mutex objMutex = new Mutex(false,"Lo cal\\" + "BokiTestin g",
                              out blnFirstInstanc e))
                              {
                              Application.Ena bleVisualStyles ();
                              >
                              }
                              >
                              Application.Set CompatibleTextR enderingDefault (false);
                              >
                              // Rest of code...
                              >
                              The idea is to hold the mutex for the whole of the time your app is
                              running.
                              >
                              --
                              Jon Skeet - <sk...@pobox.co m>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
                              If replying to the group, please do not mail me too
                              Yes, you are right, thanks!

                              Boki.

                              Comment

                              Working...