C#程序只有一个实例-打开几个文件

本文关键字:文件 几个 程序 有一个 实例 | 更新日期: 2023-09-27 18:22:25

我完成了示例中的所有内容:创建单个实例应用程序的正确方法是什么?马特·戴维斯。

但是,我有一个打开文件的应用程序。我有这个代码:

    static Mutex mutex = new Mutex(true, "{MyApplicationTest}");
    [STAThread]
    static void Main(string[] args)
    {
        if (mutex.WaitOne(TimeSpan.Zero, true))
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(args.Length == 0 ? new Form1(string.Empty) : new Form1(args[0]));
            mutex.ReleaseMutex();
        }
        else
        {
            NativeMethods.PostMessage(
            (IntPtr)NativeMethods.HWND_BROADCAST,
            NativeMethods.WM_SHOWME,
            IntPtr.Zero,
            IntPtr.Zero);
        }

在程序已经运行的情况下,如何打开下一个文件。第一个文件会自动打开。相比之下,下一次单击将只显示屏幕顶部的应用程序窗口。

C#程序只有一个实例-打开几个文件

问题已解决,感谢xxbbcchttp://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx

using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace SuperSingleInstance
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            string[] args = Environment.GetCommandLineArgs();
            SingleInstanceController controller = new SingleInstanceController();
            controller.Run(args);
        }
    }
    public class SingleInstanceController : WindowsFormsApplicationBase
    {
        public SingleInstanceController()
        {
            IsSingleInstance = true;
            StartupNextInstance += this_StartupNextInstance;
        }
        void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)
        {
            Form1 form = MainForm as Form1; //My derived form type
            form.LoadFile(e.CommandLine[1]);
        }
        protected override void OnCreateMainForm()
        {
            MainForm = new Form1();
        }
    }
}

这是我不久前为类似目的编写的一个实用程序类。(我想GlobalMutexHelper这个名字在这种情况下有点多余,这个名字有点卡住了:)。。无论如何)

由于它实现了IDisposable,您可以像一样使用它

using(var Mutexhelper=new GlobalMutexHelper("reasonably unique Name"))
{
 //Code goes here
}

这不是必须实现为IDisposable,但在我的情况下,我需要它方便因为有时"单一实例"必须取决于其他因素。

 internal class GlobalMutexHelper : IDisposable
        {
        #region Constants and Fields
        /// <summary>
        /// The access rule.
        /// </summary>
        private readonly MutexAccessRule accessRule =
            new MutexAccessRule(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null), 
                MutexRights.FullControl, 
                AccessControlType.Allow);
        /// <summary>
        /// The obj.
        /// </summary>
        private readonly Mutex obj;
        /// <summary>
        /// The sec settings.
        /// </summary>
        private readonly MutexSecurity secSettings = new MutexSecurity();
        #endregion
        #region Constructors and Destructors
        /// <summary>
        /// Initializes a new instance of the <see cref="GlobalMutexHelper"/> class.
        /// </summary>
        /// <param name="mutexname">
        /// The mutexname.
        /// </param>
        /// <exception cref="TimeoutException">
        /// </exception>
        /// <exception cref="Exception">
        /// </exception>
        public GlobalMutexHelper(string mutexname)
        {
            if (mutexname.Trim() != string.Empty)
            {
                this.secSettings.AddAccessRule(this.accessRule);
                bool isNew;
                this.obj = new Mutex(true, "Global''SomeUniqueName_" + mutexname, out isNew);
                this.obj.SetAccessControl(this.secSettings);
                if (!isNew)
                {
                    if (this.obj.WaitOne())
                    {
                        Console.WriteLine("Signalled");
                    }
                    else
                    {
                        throw new TimeoutException("Timedout while waiting for Mutex");
                    }
                }
            }
            else
            {
                throw new Exception("The mutex name cannot be empty");
            }
        }
        #endregion

        #region Public Methods and Operators
        /// <summary>
        /// The dispose.
        /// </summary>
        public void Dispose()
        {
            this.obj.ReleaseMutex();
            this.obj.Dispose();
        }
        #endregion
    }