首页 > 其他分享 >WPF implemented Single Instance via mutex and activated the existed window via FindWindow from Micr

WPF implemented Single Instance via mutex and activated the existed window via FindWindow from Micr

时间:2024-04-20 18:55:06浏览次数:9  
标签:existed via IntPtr Windows namespace System using FindWindow MainWindow

1.Remove StartUri="MainWindow.xaml" in App.xaml;

2.In the App.xaml.cs,overrive as below

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Win32;

namespace WpfApp65
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        //lpWindowName,title name FindWindow(null,"WindowsTitleName");
        [DllImport("user32", CharSet = CharSet.Unicode)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32")]
        static extern IntPtr SetForegroundWindow(IntPtr hWnd);
         
        [DllImport("user32")]
        static extern bool IsIconic(IntPtr hWnd);

        [DllImport("user32")]
        static extern bool OpenIcon(IntPtr hWnd);
        protected override void OnStartup(StartupEventArgs e)
        { 
            bool isApplicationRunning = false;
            System.Threading.Mutex mutex = new System.Threading.Mutex
                (true, System.Diagnostics.Process.GetCurrentProcess().ProcessName,
                out isApplicationRunning);
            if(!isApplicationRunning)
            {
                MessageBox.Show("The app is running!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                ActivateCurrentWindow();
                //The Shutdown() is indispensable else it will generate similar process every click
                Shutdown();
                return;
            } 
            else
            {
                MainWindow win = new MainWindow(Guid.NewGuid().ToString());
                win.Show();
            }
        }

        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
        }

        private static void ActivateCurrentWindow()
        {
            //The second parameter is Windows Title
            var other = FindWindow(null, "Single Instance");
            if (other!=IntPtr.Zero)
            {
                SetForegroundWindow(other);
                if(IsIconic(other)) 
                {
                    OpenIcon(other);
                }
            }
        }
    }
}

 

3.Update the mainwindow as below, pass the guid  value to validate whether it is the same instance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp65
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow(string str)
        {
            InitializeComponent();
            tb.Text = str;
        }
    }
}

 

The key part

 System.Threading.Mutex mutex = new System.Threading.Mutex
     (true, System.Diagnostics.Process.GetCurrentProcess().ProcessName,
     out isApplicationRunning);
//lpWindowName,title name FindWindow(null,"WindowsTitleName");
[DllImport("user32", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

 

标签:existed,via,IntPtr,Windows,namespace,System,using,FindWindow,MainWindow
From: https://www.cnblogs.com/Fred1987/p/18148006

相关文章

  • 大型场景中通过监督视图贡献加权进行多视图人物检测 Multi-View People Detection in
    Multi-ViewPeopleDetectioninLargeScenesviaSupervisedView-WiseContributionWeighting大型场景中通过监督视图贡献加权进行多视图人物检测论文urlhttps://ojs.aaai.org/index.php/AAAI/article/view/28553论文简述:这篇论文提出了一个用于大型场景中多视角人体检测......
  • 4-2 docker隔离机制-namespace
    1、使用Namespaces实现了系统环境的隔离Docker实际上是在创建容器进程时,指定了这个进程所需要启用的一组Namespace参数,这样容器就只能看到当前Namespace所限定的资源、文件、设备、状态。而对于宿主机以及其他不相干的程序,就完全看不见了http://www.dockone.io/article/8148常......
  • C++要点细细梳理——trivial:运算符优先级、switch、临时变量默认赋值等
    1.运算符优先级在C语言中,运算符的优先级决定了在表达式中各个运算符的执行顺序。当一个表达式中有多个运算符时,优先级高的运算符会先被计算。如果两个运算符的优先级相同,那么它们的结合性(从左到右或从右到左)会决定它们的计算顺序。以下是一些基本的C语言运算符优先级(从......
  • RuleEngine规则引擎底层改造AviatorScript 之函数执行
    https://gitee.com/aizuda/rule-engine-open需求:使用上述开源框架进行改造,底层更换成AviatorScript,函数实现改造。原本实现方式@OverridepublicObjectrun(ExecuteFunctionRequestexecuteTestRequest){IntegerfunctionId=executeTestRequest.ge......
  • WPF datagrid mvvm multi select via customize datagrid
    usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows;usingSystem.Windows.Controls;namespaceWpfApp39{publicclassMultiSelectDataGrid:D......
  • utilseq.h:92:30: error: ‘Iefp’ is not a class or namespace
     001、问题,make编译报错如下:utilseq.h:92:30:error:‘Iefp’isnotaclassornamespace 002、感觉像是c++版本低造成的测试一下,将gcc编译器有4.8升级到11,问题解决。升级方法:https://www.cnblogs.com/liujiaxin2018/p/16744442.html(base)[root@pc1src]#gcc......
  • DMKD: IMPROVING FEATURE-BASED KNOWLEDGE DISTILLATION FOR OBJECT DETECTION VIA DU
    摘要最近主流的掩模蒸馏方法是通过从教师网络的特征图中重建学生网络的选择性掩模区域来实现的。在这些方法中,需要适当的选择掩模区域,使重构的特征像教师特征一样具有足够的识别和表示能力。然而,以前的掩模蒸馏方法只关注空间掩模,使得得到的掩模区域偏向于空间重要性,而没有......
  • [GO-LANG] Why is my trivial program such a large binary?
     Whyismytrivialprogramsuchalargebinary?Thelinkerinthe gc toolchaincreatesstatically-linkedbinariesbydefault.AllGobinariesthereforeincludetheGoruntime,alongwiththerun-timetypeinformationnecessarytosupportdynamictypech......
  • 【Pavia】遥感图像数据集下载地址和读取数据集代码
    【Pavia】遥感图像数据集下载地址和读取数据集代码目录【Pavia】遥感图像数据集下载地址和读取数据集代码前言Pavia数据集Pavia数据集地址:Pavia数据集预览PaviaU.matPaviaU_gt.matPavia数据集的Matlab读取方式Pavia数据集中PaviaU.mat的matlab读取代码Pavia数据集中PaviaU_gt.ma......
  • WPF canvas draw lines via brush
    //xaml<Windowx:Class="WpfApp11.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mic......