How to implement single instance per machine application?

前端 未结 7 2097
無奈伤痛
無奈伤痛 2020-12-06 17:42

I have to restrict my .net 4 WPF application so that it can be run only once per machine. Note that I said per machine, not per session.
I implemented single instance ap

7条回答
  •  暖寄归人
    2020-12-06 18:20

    See below for full example of how a single instace app is done in WPF 3.5

    public class SingleInstanceApplicationWrapper :
    Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
    {
    public SingleInstanceApplicationWrapper()
    {
    // Enable single-instance mode.
    this.IsSingleInstance = true;
    }
    // Create the WPF application class.
    private WpfApp app;
    protected override bool OnStartup(
    Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
    {
    app = new WpfApp();
    app.Run();
    return false;
    }
    // Direct multiple instances.
    protected override void OnStartupNextInstance(
    Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs e)
    {
    if (e.CommandLine.Count > 0)
    {
    app.ShowDocument(e.CommandLine[0]);
    }
    }
    }
    

    Second part:

    public class WpfApp : System.Windows.Application
    {
    protected override void OnStartup(System.Windows.StartupEventArgs e)
    {
    base.OnStartup(e);
    WpfApp.current = this;
    // Load the main window.
    DocumentList list = new DocumentList();
    this.MainWindow = list;
    list.Show();
    // Load the document that was specified as an argument.
    if (e.Args.Length > 0) ShowDocument(e.Args[0]);
    }
    public void ShowDocument(string filename)
    {
    try
    {
    Document doc = new Document();
    doc.LoadFile(filename);
    doc.Owner = this.MainWindow;
    doc.Show();
    // If the application is already loaded, it may not be visible.
    // This attempts to give focus to the new window.
    doc.Activate();
    }
    catch
    {
    MessageBox.Show("Could not load document.");
    }
    }
    }
    

    Third part:

     public class Startup
        {
        [STAThread]
        public static void Main(string[] args)
        {
        SingleInstanceApplicationWrapper wrapper =
        new SingleInstanceApplicationWrapper();
        wrapper.Run(args);
        }
        }
    

    You may need to add soem references and add some using statements but it shoudl work.

    You can also download a VS example complete solution by downloading the source code of the book from here.

    Taken From "Pro WPF in C#3 2008 , Apress , Matthew MacDonald" , buy the book is gold. I did.

提交回复
热议问题