473,385 Members | 1,944 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Single Instance Form

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/Applicat...and_Management
http://www.codeproject.com/csharp/Si...pplication.asp
http://blogs.msdn.com/onoj/archive/2...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;
}
}
Feb 22 '07 #1
3 7172
Why not use a singleton pattern, its specifically for single instance only
classes.

"Mark Jerde" <Ma*******@newsgroup.nospamwrote in message
news:up*************@TK2MSFTNGP05.phx.gbl...
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/Applicat...and_Management
http://www.codeproject.com/csharp/Si...pplication.asp
http://blogs.msdn.com/onoj/archive/2...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;
}
}


Feb 22 '07 #2
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

"PokerMan" <no****@pokercat.co.ukwrote in message
news:%2***************@TK2MSFTNGP06.phx.gbl...
Why not use a singleton pattern, its specifically for single instance only
classes.

"Mark Jerde" <Ma*******@newsgroup.nospamwrote in message
news:up*************@TK2MSFTNGP05.phx.gbl...
>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/Applicat...and_Management
http://www.codeproject.com/csharp/Si...pplication.asp
http://blogs.msdn.com/onoj/archive/2...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;
}
}



Feb 22 '07 #3
PokerMan <no****@pokercat.co.ukwrote:
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.

--
Jon Skeet - <sk***@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
Feb 22 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
by: Steve Barnett | last post by:
I want to ensure that there is only ever one instance of my app running on a single PC at any time. I understand that I can achieve this by using a mutex and, if I can't take ownership of the...
1
by: Maileen | last post by:
Hi, How can i do (and test) a single instance of my form ? thanks, Maileen
5
by: Jaime Lucci | last post by:
Hi. I'm trying to put 2 forms in a single archive. For example: public class from1 .... end class public class form2 .....
9
by: MrSpock | last post by:
1. Create a new Windows Application project. 2. Open the project properties and check "Make single instance application". 3. Build. 4. Go to the release folder and run the application. 5. Try to...
1
by: Ratnesh Raval | last post by:
hi all, i've a tray app. that runs in a tray with no forms. when a user clicks on the trayicon i show main form. my question is, can i make it like the messenger applications.. so if user trys...
13
by: JohnQ | last post by:
Why would anyone write: class SomeThing // class littered with non-domain single-instancing code :( { private: SomeThing(); static SomeThing* pInstance_; public: static SomeThing*...
4
by: Andrus | last post by:
For winforms application with multiple related forms it is reasonable to create Linq database context object in start of application. Context object is released only when application exits. So...
7
by: =?Utf-8?B?TWF0dA==?= | last post by:
Hi I have an app that runs without a main form, just a notification icon, when the user clicks the icon the form is shown, and when the form is minimized it's hidden. This all works great,...
1
by: Prats | last post by:
I have a windows form application developed in C++/CLR How can I verify that only one instance of the application is running on the user system at any given time. Thanks
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.