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

标签 c# file instance

我做了所有示例:What is the correct way to create a single-instance application?作者:马特·戴维斯。

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

    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);
        }

在程序已经运行的情况下如何打开下一个文件。第一个文件自动打开。相反,下一次点击只会在屏幕顶部出现应用程序窗口。

最佳答案

问题解决了,感谢xxbbcc http://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();
        }
    }
}

关于C# 只有一个程序实例 - 打开几个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25898102/

相关文章:

C# 结构数组但不是类数组

c# - HtmlDocument.Save (HtmlAgilityPack) 输出不完整的文件

C++ ifstream帮助(简单)

java - 获取文件的最后修改日期而不是 Java 中的最后创建日期

image - 如何创建没有 EBS 的预留实例的 "Instance Store"AMI 镜像

c# - 算术运算wpf中的上溢或下溢

c# - 在右键单击菜单上打开属性页时 Visual Studio 2015 挂起

c++ - 如何获取临时/右值的地址进行复制?

haskell - 如何在不推导的情况下实例化 Eq

python - 为什么必须创建一个新的全局变量来引用 "exec"中的当前类实例?