C#SetForegroundWindow无法正常工作

亚历克斯

我使用此问题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;
                        }
                    }
                }
            }
        }
    }
}
汉斯·帕桑特

旋转自己的单实例应用程序通常是一个错误,.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);
        }
    }
}

如果用于启动第二个实例的命令行参数有任何用处(例如,在使用文件关联时的典型情况),则在事件处理程序中使用eventArgs.CommandLine

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章