C# SetForegroundWindow not working

前端 未结 2 527
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 05:17

I have restricted my C# windows application to only allow one instance to be running at a time, using this question How to force C# .net app to run only one instance in Wind

相关标签:
2条回答
  • 2020-12-07 05:51

    Spinning your own single-instance app is generally a mistake, the .NET Framework already supports it strongly and it is rock-solid, very hard to exploit. And has the feature you are looking for, a StartupNextInstance event that fires when the user starts your app again. Add a reference to Microsoft.VisualBasic and make your Program.cs file look like this:

    using System;
    using System.Windows.Forms;
    using Microsoft.VisualBasic.ApplicationServices;
    
    namespace WhatEverYouUse {
        class Program : WindowsFormsApplicationBase {
            [STAThread]
            static void Main(string[] args) {
                Application.SetCompatibleTextRenderingDefault(false);
                new Program().Start(args);
            }
            void Start(string[] args) {
                this.EnableVisualStyles = true;
                this.IsSingleInstance = true;
                this.MainForm = new Form1();
                this.Run(args);
            }
            protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {
                eventArgs.BringToForeground = true;
                base.OnStartupNextInstance(eventArgs);
            }
        }
    }
    

    If you have any use for the command line arguments that were used to start the 2nd instance, typical when you use a file association for example, then use eventArgs.CommandLine in your event handler.

    0 讨论(0)
  • 2020-12-07 05:56

    try this...

    System.Threading.Tasks.Task.Factory.StartNew(() => { SetForegroundWindow(this.Handle); });
    
    0 讨论(0)
提交回复
热议问题