Click here to Skip to main content
15,902,112 members
Home / Discussions / C#
   

C#

 
GeneralRe: File Problem in VISTA Pin
Rob Philpott30-Dec-09 22:01
Rob Philpott30-Dec-09 22:01 
GeneralRe: File Problem in VISTA Pin
Wamuti30-Dec-09 22:05
Wamuti30-Dec-09 22:05 
AnswerRe: File Problem in VISTA Pin
#realJSOP30-Dec-09 23:41
professional#realJSOP30-Dec-09 23:41 
GeneralRe: File Problem in VISTA Pin
Sipder31-Dec-09 1:38
Sipder31-Dec-09 1:38 
GeneralRe: File Problem in VISTA Pin
#realJSOP31-Dec-09 4:15
professional#realJSOP31-Dec-09 4:15 
QuestionProblem with User Control Pin
nagendrathecoder30-Dec-09 20:29
nagendrathecoder30-Dec-09 20:29 
AnswerMessage Closed Pin
30-Dec-09 21:05
stancrm30-Dec-09 21:05 
GeneralRe: Problem with User Control Pin
nagendrathecoder30-Dec-09 21:47
nagendrathecoder30-Dec-09 21:47 
AnswerRe: Problem with User Control Pin
nagendrathecoder30-Dec-09 22:03
nagendrathecoder30-Dec-09 22:03 
Questiontlbexp.exe Pin
satsumatable30-Dec-09 17:40
satsumatable30-Dec-09 17:40 
GeneralRe: tlbexp.exe [modified] Pin
Abhinav S30-Dec-09 19:34
Abhinav S30-Dec-09 19:34 
GeneralRe: tlbexp.exe Pin
satsumatable30-Dec-09 19:36
satsumatable30-Dec-09 19:36 
GeneralRe: tlbexp.exe Pin
Abhinav S30-Dec-09 21:13
Abhinav S30-Dec-09 21:13 
Questionerror while resizing uploaded image Pin
uglyeyes30-Dec-09 15:32
uglyeyes30-Dec-09 15:32 
AnswerRe: error while resizing uploaded image Pin
J a a n s30-Dec-09 19:45
professionalJ a a n s30-Dec-09 19:45 
QuestionWindows 7 SDK code Pin
Sir Dot Net30-Dec-09 14:46
Sir Dot Net30-Dec-09 14:46 
AnswerRe: Windows 7 SDK code Pin
Dave Kreskowiak30-Dec-09 16:38
mveDave Kreskowiak30-Dec-09 16:38 
QuestionA Couple of Questions Pin
Steven857930-Dec-09 14:37
Steven857930-Dec-09 14:37 
AnswerRe: A Couple of Questions Pin
Abhinav S30-Dec-09 16:29
Abhinav S30-Dec-09 16:29 
AnswerRe: A Couple of Questions Pin
petercrab30-Dec-09 18:28
petercrab30-Dec-09 18:28 
GeneralRe: A Couple of Questions Pin
Steven857930-Dec-09 19:34
Steven857930-Dec-09 19:34 
GeneralRe: A Couple of Questions Pin
ely_bob31-Dec-09 9:02
professionalely_bob31-Dec-09 9:02 
Questionsingle instance using C# and WinAPI Pin
Jassim Rahma30-Dec-09 10:47
Jassim Rahma30-Dec-09 10:47 
AnswerRe: single instance using C# and WinAPI Pin
Jimmanuel30-Dec-09 10:54
Jimmanuel30-Dec-09 10:54 
AnswerRe: single instance using C# and WinAPI Pin
DaveyM6931-Dec-09 1:43
professionalDaveyM6931-Dec-09 1:43 
There's loads of examples of this around - this is the code I use (WinForms) which is adapted from code I found somewhere (can't remember where to give credit Hmmm | :| )
C#
// SingleInstance.cs

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace YourNamespace
{
    internal static class SingleInstance
    {
        #region Fields

        private static Form applicationForm = null;
        private static string assemblyGuid = null;
        private static int message = 0;
        private static Mutex mutex = null;

        #endregion

        #region Properties

        /// <summary>
        /// Gets this assembly's GUID.
        /// </summary>
        private static string AssemblyGuid
        {
            get
            {
                if (assemblyGuid == null)
                {
                    object[] attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(GuidAttribute), false);
                    if (attributes.Length != 0)
                        assemblyGuid = ((GuidAttribute)attributes[0]).Value;
                    else
                        assemblyGuid = string.Empty;
                }
                return assemblyGuid;
            }
        }
        /// <summary>
        /// Gets the unique message that will be broadcast when another instance is rejected.
        /// </summary>
        public static int Message
        {
            get
            {
                if (message == 0)
                    message = NativeMethods.RegisterWindowMessage(String.Format("WM_SHOWFIRSTINSTANCE|{0}", AssemblyGuid));
                return message;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// If this is the only instance of this application then it will be run.
        /// If not, a message will be broadcast that the first instance can respond to.
        /// </summary>
        /// <param name="mainForm">A System.Windows.Forms.Form that represents the form to make visible.</param>
        /// <remarks>Call this from Main in Program.cs to run your app as a single instance.</remarks>
        public static void Run(Form mainForm)
        {
            Run(mainForm, false);
        }
        /// <summary>
        /// If this is the only instance of this application then it will be run.
        /// If not, a message will be broadcast that the first instance can respond to.
        /// </summary>
        /// <param name="mainForm">A System.Windows.Forms.Form that represents the form to make visible.</param>
        /// <param name="globalMutex">true to make this single instance system wide; otherwise, false.</param>
        /// <remarks>Call this from Main in Program.cs to run your app as a single instance.</remarks>
        public static void Run(Form mainForm, bool globalMutex)
        {
            if (mainForm != null)
            {
                if (Start(globalMutex))
                {
                    try
                    {
                        applicationForm = mainForm;
                        Application.Run(applicationForm);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                    Stop();
                }
            }
        }
        /// <summary>
        /// Brings the main form to the front and gives it focus.
        /// If the form is minimized or maximized it will be restored.
        /// </summary>
        public static void ShowToFront()
        {
            if (applicationForm != null)
            {
                NativeMethods.SetWindowPos(applicationForm.Handle, new IntPtr(-1), 0, 0, 0, 0, NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE);
                NativeMethods.SetWindowPos(applicationForm.Handle, new IntPtr(-2), 0, 0, 0, 0, NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE);
                NativeMethods.ShowWindow(applicationForm.Handle, NativeMethods.SW_SHOWNORMAL);
                NativeMethods.SetForegroundWindow(applicationForm.Handle);
            }
        }
        private static bool Start()
        {
            return Start(false);
        }
        private static bool Start(bool globalMutex)
        {
            bool createdNew = false;
            string name = null;
            if (globalMutex)
                name = String.Format("Global\\{0}", AssemblyGuid);
            else
                name = string.Format("Local\\{0}", AssemblyGuid);
            Mutex thisMutex = new Mutex(true, name, out createdNew);
            if (createdNew)
                mutex = thisMutex;
            else
                NativeMethods.PostMessage(
                    (IntPtr)NativeMethods.HWND_BROADCAST,
                    Message,
                    IntPtr.Zero,
                    IntPtr.Zero);
            return createdNew;
        }
        private static void Stop()
        {
            mutex.ReleaseMutex();
        }

        #endregion

        /// <summary>
        /// Win32 API functions.
        /// </summary>
        private static class NativeMethods
        {
            #region Constants

            /// <summary>
            /// The message is posted to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows.
            /// The message is not posted to child windows.
            /// </summary>
            public const int HWND_BROADCAST = 0xffff;
            /// <summary>
            /// Activates and displays a window.
            /// If the window is minimized or maximized, the system restores it to its original size and position.
            /// </summary>
            public const int SW_SHOWNORMAL = 1;
            /// <summary>
            /// Retains the current size (ignores the cx and cy parameters).
            /// </summary>
            public const int SWP_NOSIZE = 0x0001;
            /// <summary>
            /// Retains the current position (ignores X and Y parameters).
            /// </summary>
            public const int SWP_NOMOVE = 0x0002;

            #endregion

            #region Methods

            // http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx
            /// <summary>
            /// Places (posts) a message in the message queue associated with the thread that created the specified window and returns without waiting for the thread to process the message.
            /// </summary>
            /// <param name="hWnd">Handle to the window whose window procedure is to receive the message.</param>
            /// <param name="Msg">Specifies the message to be posted.</param>
            /// <param name="wParam">Additional message-specific information.</param>
            /// <param name="lParam">Additional message-specific information.</param>
            /// <returns>Nonzero if the function succeeds; otherwise, zero.</returns>
            [DllImport("user32")]
            public static extern bool PostMessage(
                IntPtr hWnd,
                int Msg,
                IntPtr wParam,
                IntPtr lParam);

            // http://msdn.microsoft.com/en-us/library/ms644947(VS.85).aspx
            /// <summary>
            /// Defines a new window message that is guaranteed to be unique throughout the system.
            /// </summary>
            /// <param name="lpString">String that specifies the message to be registered.</param>
            /// <returns>A message identifier in the range 0xC000 through 0xFFFF ff the message is successfully registered; otherwise, zero</returns>
            [DllImport("user32")]
            public static extern int RegisterWindowMessage(
                string lpString);

            // http://msdn.microsoft.com/en-us/library/ms633539(VS.85).aspx
            /// <summary>
            /// Puts the thread that created the specified window into the foreground and activates the window.
            /// </summary>
            /// <param name="hWnd">Handle to the window that should be activated and brought to the foreground.</param>
            /// <returns>Nonzero if the window was brought to the foreground; otherwise, zero.</returns>
            [DllImport("user32.dll")]
            public static extern bool SetForegroundWindow(
                IntPtr hWnd);

            // http://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx
            /// <summary>
            /// Changes the size, position, and Z order of a child, pop-up, or top-level window.
            /// </summary>
            /// <param name="hWnd">A handle to the window.</param>
            /// <param name="hWndInsertAfter">A handle to the window to precede the positioned window in the Z order.</param>
            /// <param name="X">Specifies the new position of the left side of the window, in client coordinates.</param>
            /// <param name="Y">Specifies the new position of the top of the window, in client coordinates.</param>
            /// <param name="cx">Specifies the new width of the window, in pixels.</param>
            /// <param name="cy">Specifies the new height of the window, in pixels. </param>
            /// <param name="uFlags">Specifies the window sizing and positioning flags.</param>
            /// <returns>Nonzero if the function succeeds; otherwise, zero.</returns>
            [DllImport("user32.dll")]
            public static extern bool SetWindowPos(
                IntPtr hWnd,
                IntPtr hWndInsertAfter,
                int X,
                int Y,
                int cx,
                int cy,
                int uFlags);

            // http://msdn.microsoft.com/en-us/library/ms633548(VS.85).aspx
            /// <summary>
            /// Sets the specified window's show state.
            /// </summary>
            /// <param name="hWnd">Handle to the window.</param>
            /// <param name="nCmdShow">Specifies how the window is to be shown.</param>
            /// <returns>Nonzero if the window was previously visible; otherwise, zero.</returns>
            [DllImport("user32.dll")]
            public static extern bool ShowWindow(
                IntPtr hWnd,
                int nCmdShow);

            #endregion
        }
    }
}
A small modification to Program.cs
C#
// Modified Program.cs
using System;
using System.Windows.Forms;

namespace YourNamespace
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // Use SingleInstance class instead of Application
            SingleInstance.Run(new FormMain());
        }
    }
}
Then override WndProc in the main form to receive the message so you can bring it to the front
C#
//  Added to FormMain.cs

protected override void WndProc(ref Message message)
{
    if (message.Msg == SingleInstance.Message)
        SingleInstance.ShowToFront();
    base.WndProc(ref message);
}


Dave

BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
Why are you using VB6? Do you hate yourself? (Christian Graus)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.