C#SetForegroundWindow不工作

Ale*_*lex 1 c#

我已经限制我的C#windows应用程序只允许一次运行一个实例,使用这个问题如何强制C#.net应用程序在Windows中只运行一个实例?

它运行良好,并且不允许同时运行多个应用程序实例.

问题是如果用户试图打开应用程序的第二个实例,我希望当前活动的实例能够出现在前面.

我工作的问题似乎解决了这个问题,但它对我不起作用.

我认为这是因为我的应用程序不符合允许该方法的标准:SetForegroundWindow 工作.

我的问题是,我怎样才能做到这一点.我的代码如下:

using System    ;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace RTRFIDListener_Client
{
    static class Program
    {
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            bool createdNew = true;

            using (Mutex mutex = new Mutex(true, "RTRFIDListener_Client", out createdNew))
            {
                if (createdNew)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new frm_Main());
                }
                else
                {
                    Process current = Process.GetCurrentProcess();
                    foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                    {
                        if (process.Id != current.Id)
                        {
                            SetForegroundWindow(process.MainWindowHandle);
                            break;
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 6

旋转您自己的单实例应用程序通常是一个错误,.NET Framework已经强烈支持它,并且它非常坚固,非常难以利用.并且具有您正在寻找的功能,一个StartupNextInstance事件,当用户再次启动您的应用程序时会触发该事件.添加对Microsoft.VisualBasic的引用,并使您的Program.cs文件如下所示:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您对用于启动第二个实例的命令行参数有任何用处,例如,当您使用文件关联时,则通常在事件处理程序中使用eventArgs.CommandLine.