WPF只能打开一个程序,第二次打开直接激活已运行的窗口,不新开

打开项目里的 App.xaml.cs,改成下面这样:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;

namespace FileManagerUI
{
    public partial class App : Application
    {
        // 定义一个互斥量,保证全局唯一
        private static Mutex _mutex;

        // 激活已运行的窗口(Win32 API)
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        private const int SW_RESTORE = 9;

        protected override void OnStartup(StartupEventArgs e)
        {
            // 这里的名字可以随便改,但必须唯一
            string mutexName = "FileManagerUI_SingleInstance";

            _mutex = new Mutex(true, mutexName, out bool isNewInstance);

            if (!isNewInstance)
            {
                // 已经有程序在运行 → 激活它
                Process current = Process.GetCurrentProcess();
                foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        IntPtr handle = process.MainWindowHandle;
                        ShowWindow(handle, SW_RESTORE);      // 还原窗口
                        SetForegroundWindow(handle);          // 激活到最前
                        break;
                    }
                }

                // 关闭当前这个新实例
                Environment.Exit(0);
                return;
            }

            base.OnStartup(e);
        }
    }
}

二、App.xaml 保持默认

<Application x:Class="FileManagerUI.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="IEasePanel.xaml">
</Application>

三、效果(你要的)

  • 只能打开一个程序
  • 双击第二次 → 不会新开
  • 自动把已经打开的窗口激活、显示到最前面
  • 完全不影响你现有的功能

四、如果你需要【中文提示】版本

第二次打开时弹出提示:
if (!isNewInstance)
{
    MessageBox.Show("程序已在运行中!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
    Environment.Exit(0);
    return;
}

 

posted @ 2026-06-07 21:46  工易  阅读(43)  评论(0)    收藏  举报