c# - 我怎样才能执行我的应用程序的单个实例?

标签 c# .net winapi focus

如何确保我的应用程序只有一个实例,并在尝试打开第二个实例时将焦点设置到它?

我试过:

public partial class Form1 : Form {

    [DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
    public static extern
    IntPtr FindWindow(String lpClassName, String lpWindowName);

    [DllImport("USER32.DLL")]
    public static extern
    Boolean SetForegroundWindow(IntPtr hWnd);

    private void Form1_Load(object sender, EventArgs e)
    {
        bool isRunning = Process.GetProcesses()
                                .Where(p => p.MainWindowTitle.Contains(Text))
                                .Count() > 1;

        if (isRunning)
        {
            FocusWindow(Text);
            Application.Exit();
        }
    }

    public static void FocusWindow(string title)
    {
        SetForegroundWindow(FindWindow(null, title));
    }
}

这不是聚焦应用。我该如何解决这个问题?

最佳答案

您可能想改用 Mutex,这样可以避免以稍微不可靠的方式搜索窗口(假设您重命名主窗体或打开另一个窗体)。

bool createdNew;
Mutex m = new Mutex(true, "SomeNameHere", out createdNew);

if (!createdNew)
{
    // Application already running. Call it and ask to show it's form.
    IpcClientChannel clientChannel = new IpcClientChannel();
    ChannelServices.RegisterChannel(clientChannel, true);

    RemotingConfiguration.RegisterWellKnownClientType(typeof(ExchangeBase), "ipc://SomeNameHere/YourAppBase");

    ExchangeBase Exchange = new ExchangeBase();
    Exchange.ShowForm();
}
else
{
    IpcServerChannel serverChannel = new IpcServerChannel("SomeNameHere");
    ChannelServices.RegisterChannel(serverChannel, true);
    RemotingConfiguration.RegisterWellKnownServiceType(typeof(ExchangeBase), "YourAppBase", WellKnownObjectMode.SingleCall);

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    MainForm = new FormMain();
    if (!MainForm.StopLoading)
    {
        Application.Run(MainForm);

        // Keep the mutex reference alive until the termination of the program.
        GC.KeepAlive(m);
    }
}

关于c# - 我怎样才能执行我的应用程序的单个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8856441/

相关文章:

c++ - 编辑/删除 protected 注册表键值

.net - WPF Singleton ValueConverters 性能影响

c++ - 子类化 SHBrowseForFolder 并处理 WM_NOTIFY

c# - 访问当前在 Outlook 2007 中选择的文本

c# - 在 C# 中获取套接字对象的流

c# - MongoDB:推荐在 .NET 上使用的驱动程序?

c# - 将 Gtk# 对话框放置在 Gtk 窗口的中心

c++ - TrackPopupMenu中的助记词如何获取?

c# - ASP.NET DateTime.Now 卡住在单个页面上

c# - 如何在 C# 中进行异常处理和跟踪