Link to home
Start Free TrialLog in
Avatar of dungnk77
dungnk77

asked on

C#: Disallow multi-instances and display the BrowseForFolder dialog

In C#:
_ How to disable multi-instances of an C# application at the same time?
_ How to display the BrowseForFolder? and how to explore the specified folder at start of displaying.
ASKER CERTIFIED SOLUTION
Avatar of Fahad Mukhtar
Fahad Mukhtar
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

** note..

using System.Diagnostics;
Avatar of _TAD_
_TAD_



<excerpt from
http://search.experts-exchange.com/questions/20614186/prevent-second-app-instance-when-in-c.html >




Mutex (from System.Threading) can be used to simply stop the the new instance from running.





If you also want to bring the FIRST instance to the foreground, you also need FindWindow and SetForegroundWindow, from user32.dll.

Here's a sample that does these.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.Runtime.InteropServices;

namespace OnlyOneInstance
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {

         [DllImport("User32",EntryPoint="FindWindow")]
         private static extern IntPtr FindWindow(string lpClassName,string lpWindowName);

         [DllImport("User32",EntryPoint="SetForegroundWindow")]
         private static extern bool SetForegroundWindow(IntPtr hWnd);

         /// <summary>
         /// Required designer variable.
         /// </summary>
         private System.ComponentModel.Container components = null;

         public Form1()
         {
              //
              // Required for Windows Form Designer support
              //
              InitializeComponent();

              //
              // TODO: Add any constructor code after InitializeComponent call
              //
         }

         /// <summary>
         /// Clean up any resources being used.
         /// </summary>
         protected override void Dispose( bool disposing )
         {
              if( disposing )
              {
                   if (components != null)
                    {
                        components.Dispose();
                   }
              }
              base.Dispose( disposing );
         }

         #region Windows Form Designer generated code
         /// <summary>
         /// Required method for Designer support - do not modify
         /// the contents of this method with the code editor.
         /// </summary>
         private void InitializeComponent()
         {
              this.components = new System.ComponentModel.Container();
              this.Size = new System.Drawing.Size(300,300);
              this.Text = "Form1";
         }
         #endregion

         /// <summary>
         /// The main entry point for the application.
         /// </summary>
         [STAThread]
         static void Main()
          {
              Mutex mutex = new Mutex(false, "ONLY LET SINGLE INSTANCE RUN");
              bool Running = !mutex.WaitOne(0, false);
              if (Running)
              {
                   bool ret;
                   IntPtr hWnd = FindWindow(null, "Form1");
                   if(hWnd != IntPtr.Zero)
                        ret = SetForegroundWindow(hWnd);
              }
              else
               Application.Run(new Form1());
         }
    }
}


You are looking for the xxxFileDialog class.

<exerpt from MSDN>

FileDialog is an abstract class, and cannot be instantiated directly. Additionally, you cannot inherit from this class. To create a dialog to select or save a file use OpenFileDialog or SaveFileDialog.


protected void button1_Click(object sender, System.EventArgs e)
{
    Stream myStream;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\" ;
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        if((myStream = openFileDialog1.OpenFile())!= null)
        {
            // Insert code to read the stream here.
            myStream.Close();
        }
    }
}
[C++, JScript] No example is available for C++ or JScript. To view a Visual Basic or C# example, click the Language Filter button  in the upper-left corner of the page.




Here is another website on using mutext to disable multiple application instances


http://www.developerfusion.com/show/1716/7/
You should be able to do away with the DLL imports and just use the built in functions for a form.

(from Desp code)
...
if (AllProcesses.Length)>1) // if the process is running
{
    this.Activate();
    this.BringToFront();
}
else
{
    Application.Run(new Form1());
}
...

On Windows systems the activate will make it flash if it is in the taskbar area.
Avatar of dungnk77

ASKER

Thank you much for all your helps.
_ #1 - to disable multi-instances: it works very well.
_ #2 - to display BrowseForFolder: I mean that I want to display the dialog box allowing the user to select a folder. I have just found the way to do that. But there is still small problem: how to display the treeview and go straight to the specified folder (e.g. "C:\My folder")?
The following code is what I use:

      public class BrowseForFolder : FolderNameEditor
      {
            #region Enumerations

            public enum BrowserStylesEnum : int
            {
                  BrowseForComputer = 0x00001000,
                  BrowseForEverything = 0x00004000,
                  BrowseForPrinter = 0x00002000,
                  RestrictToDomain = 0x00000002,
                  RestrictToFilesystem = 0x00000001,
                  RestrictToSubfolders = 0x00000008,
                  ShowTextBox = 0x00000010,
            }
            public enum FoldersEnum
            {
                  Desktop = 0x00000000,
                  Favorites = 0x00000006,
                  MyComputer = 0x00000011,
                  MyDocuments = 0x00000005,
                  MyPictures = 0x00000027,
                  NetAndDialUpConnections = 0x00000031,
                  NetworkNeighborhood = 0x00000012,
                  Printers = 0x00000004,
                  Recent = 0x00000008,
                  SendTo = 0x00000009,
                  StartMenu = 0x0000000B,
                  Templates = 0x00000015
            }
            #endregion Enumerations

            private FolderNameEditor.FolderBrowser m_oFolderBrowser = new FolderBrowser();

            #region Properties, methods

            public string Description
            {
                  get
                  {
                        return m_oFolderBrowser.Description;
                  }
                  set
                  {
                        m_oFolderBrowser.Description = value;
                  }
            }

            public string DirectoryPath
            {
                  get
                  {
                        return m_oFolderBrowser.DirectoryPath;
                  }
            }

            public FoldersEnum StartLocation
            {
                  get
                  {
                        return (FoldersEnum)(int)m_oFolderBrowser.StartLocation;
                  }
                  set
                  {
                        m_oFolderBrowser.StartLocation = (FolderBrowserFolder)(int)value;
                  }
            }

            public BrowserStylesEnum Style
            {
                  get
                  {
                        return (BrowserStylesEnum)(int)m_oFolderBrowser.Style;
                  }
                  set
                  {
                        m_oFolderBrowser.Style = (FolderBrowserStyles)(int)value;
                  }
            }

            public DialogResult ShowDialog()
            {
                  return m_oFolderBrowser.ShowDialog();
            }

            public DialogResult ShowDialog(IWin32Window frmOwner)
            {
                  return m_oFolderBrowser.ShowDialog(frmOwner);
            }

            public BrowseForFolder()
            {
            }

            ~BrowseForFolder()
            {
                  m_oFolderBrowser.Dispose();
            }
   
            #endregion Properties, methods
   
      }

            public static string BrowseFolders(BrowseForFolder.BrowserStylesEnum nStyle, BrowseForFolder.FoldersEnum nStartLocation, string strPrompt)
            {
                  BrowseForFolder oFolderDialog = new BrowseForFolder();

                  if (nStyle != 0)
                  {
                        oFolderDialog.Style = nStyle;
                  }

                  // Havenot found out the way to go straight to the specified folder!!
                  oFolderDialog.StartLocation = nStartLocation;

                  oFolderDialog.Description = strPrompt;

                  oFolderDialog.ShowDialog();

                  return oFolderDialog.DirectoryPath;
            }