What is the best way to make one instance application in .net?

Possible duplicates:
What is the correct way to create one instance of the application? Prevent multiple instances of this application in .NET?

Check if another process with the same name exists? (What if the user does not have permission to do this?)

Burn the file to disk and delete it before exiting? (how about abnormal termination?)

What would be the best practice for this?

+3
source share
5 answers

You can use mutex.

bool firstInstance = true;
using (Mutex mutex = new Mutex(true, "MyApplicationName", out firstInstance))
{
    if (firstInstance)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
    else
    {
        // Another instance loaded
    }
}
+6
source

Process class GetProcessesByName , .

0

. , WPF, WinForms:

  • WindowsFormsApplicationsBase ( )
  • Mutex ( )
  • ( )

WindowsFormsApplicationsBase:
http://www.openwinforms.com/single_instance_application.html

Mutex :
http://www.ravinderweb.com/page/Single-Instance-of-the-Application-using-C-Trick-and-Mutex.aspx

, , , .

0

, , .

, . , , :

  • WindowStation

, Windows Forms. P/Invoke , Mutex:

  • (, GUID)

  • Mutex, .

  • EnumWindows P/Invoke .

  • EnumWindows GetProp P/Invoke , . GetProp (.. ), (PostMessage (... SC_RESTORE...), SetForegroundWindow, SetFocus), .

  • , SetProp P/Invoke, .

  • .

In my use case, this solution is better than just saving the mutex for the lifetime of the process, because it makes it possible to activate the previous instance if the user starts the second instance, and not just leaves it. Using GetProp / SetProp gives you a way to identify a process instance without relying on the process name.

0
source

Source: https://habr.com/ru/post/1712893/


All Articles