In winform, only one instance can be run in this way:
1. First, add the following namespace:
Using System. Threading;
2. modify the system Main function as follows:
Bool bCreatedNew;
// Create a new mutex using specific mutex name
Mutex m = new Mutex (false, "myUniqueName", out bCreatedNew );
If (bCreatedNew)
Application. Run (new yourFormName ());
What should I do in wpf?
After I posted a post on the Microsoft Forum, some experts proposed the following solutions. After I tried this method, I posted it to share it with you. There are other solutions that can be written for discussion:
First, reference Microsoft. VisualBasic
Create a class single
Public class single: Microsoft. VisualBasic. ApplicationServices. WindowsFormsApplicationBase
{
App;
Public single ()
{
This. IsSingleInstance = true;
}
Protected override bool OnStartup (Microsoft. VisualBasic. ApplicationServices. StartupEventArgs eventArgs)
{
A = new App ();
A. InitializeComponent ();
A. Run ();
Return false;
}
Protected override void OnStartupNextInstance (Microsoft. VisualBasic. ApplicationServices. StartupNextInstanceEventArgs eventArgs)
{
Base. OnStartupNextInstance (eventArgs );
A. activate ();
}
}
App. cs
Public partial class App: Application
{
Protected override void OnStartup (StartupEventArgs e)
{
Base. OnStartup (e );
Window1 w = new Window1 ();
W. Show ();
}
Public void activate ()
{
MainWindow. Activate ();
}
Private void Application_SessionEnding (object sender, SessionEndingCancelEventArgs e)
{
}
Private void Application_Startup (object sender, StartupEventArgs e)
{
}
Private void Application_Exit (object sender, ExitEventArgs e)
{
}
}
App. g. cs
[System. STAThreadAttribute ()]
[System. Diagnostics. DebuggerNonUserCodeAttribute ()]
Public static void Main (string [] ){
Single s = new single ();
S. Run ();
}
At the beginning of the operation, although there is no new instance after clicking again, there are two windows instances every time. Remove the StartupUri attribute in app. xaml.
Author: fwj316891124