内容来自:https://codereview.stackexchange.com/questions/20871/single-instance-wpf-application

第一步:添加System.RunTime.Remoting引用

第二步:新建一个类class1.cs(按自己想法命名)

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading; namespace SingleWPF
{
internal enum WM
{
NULL = 0x0000,
CREATE = 0x0001,
DESTROY = 0x0002,
MOVE = 0x0003,
SIZE = 0x0005,
ACTIVATE = 0x0006,
SETFOCUS = 0x0007,
KILLFOCUS = 0x0008,
ENABLE = 0x000A,
SETREDRAW = 0x000B,
SETTEXT = 0x000C,
GETTEXT = 0x000D,
GETTEXTLENGTH = 0x000E,
PAINT = 0x000F,
CLOSE = 0x0010,
QUERYENDSESSION = 0x0011,
QUIT = 0x0012,
QUERYOPEN = 0x0013,
ERASEBKGND = 0x0014,
SYSCOLORCHANGE = 0x0015,
SHOWWINDOW = 0x0018,
ACTIVATEAPP = 0x001C,
SETCURSOR = 0x0020,
MOUSEACTIVATE = 0x0021,
CHILDACTIVATE = 0x0022,
QUEUESYNC = 0x0023,
GETMINMAXINFO = 0x0024, WINDOWPOSCHANGING = 0x0046,
WINDOWPOSCHANGED = 0x0047, CONTEXTMENU = 0x007B,
STYLECHANGING = 0x007C,
STYLECHANGED = 0x007D,
DISPLAYCHANGE = 0x007E,
GETICON = 0x007F,
SETICON = 0x0080,
NCCREATE = 0x0081,
NCDESTROY = 0x0082,
NCCALCSIZE = 0x0083,
NCHITTEST = 0x0084,
NCPAINT = 0x0085,
NCACTIVATE = 0x0086,
GETDLGCODE = 0x0087,
SYNCPAINT = 0x0088,
NCMOUSEMOVE = 0x00A0,
NCLBUTTONDOWN = 0x00A1,
NCLBUTTONUP = 0x00A2,
NCLBUTTONDBLCLK = 0x00A3,
NCRBUTTONDOWN = 0x00A4,
NCRBUTTONUP = 0x00A5,
NCRBUTTONDBLCLK = 0x00A6,
NCMBUTTONDOWN = 0x00A7,
NCMBUTTONUP = 0x00A8,
NCMBUTTONDBLCLK = 0x00A9, SYSKEYDOWN = 0x0104,
SYSKEYUP = 0x0105,
SYSCHAR = 0x0106,
SYSDEADCHAR = 0x0107,
COMMAND = 0x0111,
SYSCOMMAND = 0x0112, MOUSEMOVE = 0x0200,
LBUTTONDOWN = 0x0201,
LBUTTONUP = 0x0202,
LBUTTONDBLCLK = 0x0203,
RBUTTONDOWN = 0x0204,
RBUTTONUP = 0x0205,
RBUTTONDBLCLK = 0x0206,
MBUTTONDOWN = 0x0207,
MBUTTONUP = 0x0208,
MBUTTONDBLCLK = 0x0209,
MOUSEWHEEL = 0x020A,
XBUTTONDOWN = 0x020B,
XBUTTONUP = 0x020C,
XBUTTONDBLCLK = 0x020D,
MOUSEHWHEEL = 0x020E, CAPTURECHANGED = 0x0215, ENTERSIZEMOVE = 0x0231,
EXITSIZEMOVE = 0x0232, IME_SETCONTEXT = 0x0281,
IME_NOTIFY = 0x0282,
IME_CONTROL = 0x0283,
IME_COMPOSITIONFULL = 0x0284,
IME_SELECT = 0x0285,
IME_CHAR = 0x0286,
IME_REQUEST = 0x0288,
IME_KEYDOWN = 0x0290,
IME_KEYUP = 0x0291, NCMOUSELEAVE = 0x02A2, DWMCOMPOSITIONCHANGED = 0x031E,
DWMNCRENDERINGCHANGED = 0x031F,
DWMCOLORIZATIONCOLORCHANGED = 0x0320,
DWMWINDOWMAXIMIZEDCHANGE = 0x0321, #region Windows 7
DWMSENDICONICTHUMBNAIL = 0x0323,
DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326,
#endregion USER = 0x0400, // This is the hard-coded message value used by WinForms for Shell_NotifyIcon.
// It's relatively safe to reuse.
TRAYMOUSEMESSAGE = 0x800, //WM_USER + 1024
APP = 0x8000,
} [SuppressUnmanagedCodeSecurity]
internal static class NativeMethods
{
/// <summary>
/// Delegate declaration that matches WndProc signatures.
/// </summary>
public delegate IntPtr MessageHandler(WM uMsg, IntPtr wParam, IntPtr lParam, out bool handled); [DllImport("shell32.dll", EntryPoint = "CommandLineToArgvW", CharSet = CharSet.Unicode)]
private static extern IntPtr _CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string cmdLine, out int numArgs); [DllImport("kernel32.dll", EntryPoint = "LocalFree", SetLastError = true)]
private static extern IntPtr _LocalFree(IntPtr hMem); public static string[] CommandLineToArgvW(string cmdLine)
{
IntPtr argv = IntPtr.Zero;
try
{
int numArgs = ; argv = _CommandLineToArgvW(cmdLine, out numArgs);
if (argv == IntPtr.Zero)
{
throw new Win32Exception();
}
var result = new string[numArgs]; for (int i = ; i < numArgs; i++)
{
IntPtr currArg = Marshal.ReadIntPtr(argv, i * Marshal.SizeOf(typeof(IntPtr)));
result[i] = Marshal.PtrToStringUni(currArg);
} return result;
}
finally
{ IntPtr p = _LocalFree(argv);
// Otherwise LocalFree failed.
// Assert.AreEqual(IntPtr.Zero, p);
}
} } public interface ISingleInstanceApp
{
bool SignalExternalCommandLineArgs(IList<string> args);
} /// <summary>
/// This class checks to make sure that only one instance of
/// this application is running at a time.
/// </summary>
/// <remarks>
/// Note: this class should be used with some caution, because it does no
/// security checking. For example, if one instance of an app that uses this class
/// is running as Administrator, any other instance, even if it is not
/// running as Administrator, can activate it with command line arguments.
/// For most apps, this will not be much of an issue.
/// </remarks>
public static class SingleInstance<TApplication>
where TApplication : Application, ISingleInstanceApp {
#region Private Fields /// <summary>
/// String delimiter used in channel names.
/// </summary>
private const string Delimiter = ":"; /// <summary>
/// Suffix to the channel name.
/// </summary>
private const string ChannelNameSuffix = "SingeInstanceIPCChannel"; /// <summary>
/// Remote service name.
/// </summary>
private const string RemoteServiceName = "SingleInstanceApplicationService"; /// <summary>
/// IPC protocol used (string).
/// </summary>
private const string IpcProtocol = "ipc://"; /// <summary>
/// Application mutex.
/// </summary>
private static Mutex singleInstanceMutex; /// <summary>
/// IPC channel for communications.
/// </summary>
private static IpcServerChannel channel; /// <summary>
/// List of command line arguments for the application.
/// </summary>
private static IList<string> commandLineArgs; #endregion #region Public Properties /// <summary>
/// Gets list of command line arguments for the application.
/// </summary>
public static IList<string> CommandLineArgs
{
get { return commandLineArgs; }
} #endregion #region Public Methods /// <summary>
/// Checks if the instance of the application attempting to start is the first instance.
/// If not, activates the first instance.
/// </summary>
/// <returns>True if this is the first instance of the application.</returns>
public static bool InitializeAsFirstInstance(string uniqueName)
{
commandLineArgs = GetCommandLineArgs(uniqueName); // Build unique application Id and the IPC channel name.
string applicationIdentifier = uniqueName + Environment.UserName; string channelName = String.Concat(applicationIdentifier, Delimiter, ChannelNameSuffix); // Create mutex based on unique application Id to check if this is the first instance of the application.
bool firstInstance;
singleInstanceMutex = new Mutex(true, applicationIdentifier, out firstInstance);
if (firstInstance)
{
CreateRemoteService(channelName);
}
else
{
SignalFirstInstance(channelName, commandLineArgs);
} return firstInstance;
} /// <summary>
/// Cleans up single-instance code, clearing shared resources, mutexes, etc.
/// </summary>
public static void Cleanup()
{
if (singleInstanceMutex != null)
{
singleInstanceMutex.Close();
singleInstanceMutex = null;
} if (channel != null)
{
ChannelServices.UnregisterChannel(channel);
channel = null;
}
} #endregion #region Private Methods /// <summary>
/// Gets command line args - for ClickOnce deployed applications, command line args may not be passed directly, they have to be retrieved.
/// </summary>
/// <returns>List of command line arg strings.</returns>
private static IList<string> GetCommandLineArgs(string uniqueApplicationName)
{
string[] args = null;
if (AppDomain.CurrentDomain.ActivationContext == null)
{
// The application was not clickonce deployed, get args from standard API's
args = Environment.GetCommandLineArgs();
}
else
{
// The application was clickonce deployed
// Clickonce deployed apps cannot recieve traditional commandline arguments
// As a workaround commandline arguments can be written to a shared location before
// the app is launched and the app can obtain its commandline arguments from the
// shared location
string appFolderPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName); string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt");
if (File.Exists(cmdLinePath))
{
try
{
using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode))
{
args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
} File.Delete(cmdLinePath);
}
catch (IOException)
{
}
}
} if (args == null)
{
args = new string[] { };
} return new List<string>(args);
} /// <summary>
/// Creates a remote service for communication.
/// </summary>
/// <param name="channelName">Application's IPC channel name.</param>
private static void CreateRemoteService(string channelName)
{
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props = new Dictionary<string, string>(); props["name"] = channelName;
props["portName"] = channelName;
props["exclusiveAddressUse"] = "false"; // Create the IPC Server channel with the channel properties
channel = new IpcServerChannel(props, serverProvider); // Register the channel with the channel services
ChannelServices.RegisterChannel(channel, true); // Expose the remote service with the REMOTE_SERVICE_NAME
IPCRemoteService remoteService = new IPCRemoteService();
RemotingServices.Marshal(remoteService, RemoteServiceName);
} /// <summary>
/// Creates a client channel and obtains a reference to the remoting service exposed by the server -
/// in this case, the remoting service exposed by the first instance. Calls a function of the remoting service
/// class to pass on command line arguments from the second instance to the first and cause it to activate itself.
/// </summary>
/// <param name="channelName">Application's IPC channel name.</param>
/// <param name="args">
/// Command line arguments for the second instance, passed to the first instance to take appropriate action.
/// </param>
private static void SignalFirstInstance(string channelName, IList<string> args)
{
IpcClientChannel secondInstanceChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(secondInstanceChannel, true); string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName; // Obtain a reference to the remoting service exposed by the server i.e the first instance of the application
IPCRemoteService firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl); // Check that the remote service exists, in some cases the first instance may not yet have created one, in which case
// the second instance should just exit
if (firstInstanceRemoteServiceReference != null)
{
// Invoke a method of the remote service exposed by the first instance passing on the command line
// arguments and causing the first instance to activate itself
firstInstanceRemoteServiceReference.InvokeFirstInstance(args);
}
} /// <summary>
/// Callback for activating first instance of the application.
/// </summary>
/// <param name="arg">Callback argument.</param>
/// <returns>Always null.</returns>
private static object ActivateFirstInstanceCallback(object arg)
{
// Get command line args to be passed to first instance
IList<string> args = arg as IList<string>;
ActivateFirstInstance(args);
return null;
} /// <summary>
/// Activates the first instance of the application with arguments from a second instance.
/// </summary>
/// <param name="args">List of arguments to supply the first instance of the application.</param>
private static void ActivateFirstInstance(IList<string> args)
{
// Set main window state and process command line args
if (Application.Current == null)
{
return;
} ((TApplication)Application.Current).SignalExternalCommandLineArgs(args);
} #endregion #region Private Classes /// <summary>
/// Remoting service class which is exposed by the server i.e the first instance and called by the second instance
/// to pass on the command line arguments to the first instance and cause it to activate itself.
/// </summary>
private class IPCRemoteService : MarshalByRefObject
{
/// <summary>
/// Activates the first instance of the application.
/// </summary>
/// <param name="args">List of arguments to pass to the first instance.</param>
public void InvokeFirstInstance(IList<string> args)
{
if (Application.Current != null)
{
// Do an asynchronous call to ActivateFirstInstance function
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Normal, new DispatcherOperationCallback(SingleInstance<TApplication>.ActivateFirstInstanceCallback), args);
}
} /// <summary>
/// Remoting Object's ease expires after every 5 minutes by default. We need to override the InitializeLifetimeService class
/// to ensure that lease never expires.
/// </summary>
/// <returns>Always null.</returns>
public override object InitializeLifetimeService()
{
return null;
}
} #endregion
}
}

第三步:在App.xml.cs中操作:

1:实现接口:ISingleInstanceApp

2:添加以下代码

 // TODO: Make this unique!
private const string Unique = "Change this to something that uniquely identifies your program."; [STAThread]
public static void Main()
{
if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
{
var application = new App();
application.InitializeComponent();
application.Run(); // Allow single instance code to perform cleanup operations
SingleInstance<App>.Cleanup();
}
} #region ISingleInstanceApp Members
public bool SignalExternalCommandLineArgs(IList<string> args)
{
// Bring window to foreground
if (this.MainWindow.WindowState == WindowState.Minimized)
{
this.MainWindow.WindowState = WindowState.Normal;
} this.MainWindow.Activate();
return true;
}
#endregion

注:如果只是打开一个窗口没有其他的操作,实现

SignalExternalCommandLineArgs方法为:
public bool SignalExternalCommandLineArgs(IList<string> args)
{ return true;
}

如果是打开一个窗口,重复打开置顶窗口,实现方法为:

public bool SignalExternalCommandLineArgs(IList<string> args)
{
// Bring window to foreground
if (this.MainWindow.WindowState == WindowState.Minimized)
{
this.MainWindow.WindowState = WindowState.Normal;
} this.MainWindow.Activate();
return true;
}

第四步:将App.xaml的生成方式修改为Page

第五步:将项目的属性->应用程序->启动对象,选择为自己项目名称.App

WPF实现只打开一个窗口,并且重复打开时已经打开的窗口置顶的更多相关文章

  1. 当打开一个.h或.cpp文件时, Solution Explorer就自动展开文件所在的目录

    当打开一个.h或.cpp文件时,  Solution Explorer就自动展开文件所在的目录: 如果不想展开: Tools           -> Options           -&g ...

  2. C# 只运行一个实例 ShowWindowAsync 窗体隐藏时失效 解决方案

    如果窗体已经隐藏,那么利用instance.MainWindowHandle得到的句柄为空,继而ShowWindowAsync 操作失败 不过我们可以使用FindWindow来查找到指定窗体的句柄 只 ...

  3. WPF程序只运行一个实例

    1.WPF程序在 启动窗口的构造函数执行InitializeComponent之前判断是否已经存在实例 不涉及服务器情况,可直接进行判断(不在mainwindow的构造函数中判断) // public ...

  4. 关于WPF程序只运行一个实例的方法

    找到的方法有两种: 1)http://www.cnblogs.com/liuyazhou/archive/2009/11/02/1594364.html 2)http://codereview.sta ...

  5. 运行vs时打开一个浏览器窗口,而不是在原有窗口上打开一个标签

    1.运行vs时打开一个浏览器窗口,而不是在原有窗口上打开一个标签,结束调试时窗口又关闭了,特别麻烦. 在用swagger调试接口时,好不容易输入了测试数据,然而窗口关闭了,再次调试又得重新输入. 解决 ...

  6. fopen()函数以"a+"方式打开一个不存在的文件后读写出现问题

    问题:在完成课后习题的时候,使用fopen()函数以"a+"方式打开一个不存在的文件时,写入.读取出现错误: //添加用户输入单词后,在单词头加入编号,确保编号跟着前面的开始排序 ...

  7. DoModal时带出次级窗口闪现

    最近在做MFC 界面开发. 在一个CDialog窗口DoModal模态显示时, 会将次级窗口带出闪现(比如将一个窗口active, 然后点击我现在程序需要弹框的按钮,弹出弹出正常,但原来active的 ...

  8. 关于bootstrap modal 垂直滚动条 每次打开后不置顶的问题

    打开modal时,滚动条默认没有置顶. 查了很久,网上找了很多资料都没有解决. 经分析是需要在modal的消失事件中添加让滚动条置顶的方法.

  9. VC 窗口置顶并激活为当前窗体

    转载请注明来源:https://www.cnblogs.com/hookjc/ if (this != GetForegroundWindow())                           ...

随机推荐

  1. python epoll方式tcp连接回发消息

    # -*- coding:utf-8 -*- import socket import select class testserver(): def __init__(self): self.serv ...

  2. kafka单机安装和启动

    1.下载并解压到/usr/local/src目录下 2.运行kafka需要使用Zookeeper,先启动Zookeeper,如果没有Zookeeper,可以使用kafka自带打包和配置好的Zookee ...

  3. 补记:完成了NG的SP1的全部内容 开始第二周

    DL本质上就是多层的Logistics Regression with different activation function and nicely designed back propagati ...

  4. 团队Github实战训练

    班级:软件工程1916|W 作业:团队Github实战训练 团队名称:SkyReach Github地址:Github地址 贡献比例表 队员学号 队员姓名 此次活动任务 贡献比例 221600106 ...

  5. Beta 冲刺(6/7)

    目录 摘要 团队部分 个人部分 摘要 队名:小白吃 组长博客:hjj 作业博客:beta冲刺(6/7) 团队部分 后敬甲(组长) 过去两天完成了哪些任务 ppt制作 视频拍摄 接下来的计划 准备答辩 ...

  6. 【interview】汉诺塔学递归

    https://www.cnblogs.com/yanlingyin/archive/2011/11/14/2247594.html https://www.cnblogs.com/dmego/p/5 ...

  7. Java基础——Instanceof 运算符

    Instanceof 运算符 java 中的instanceof 运算符是用来在运行时指出对象是否为特定类的一个实例 instanceof运算返回值:boolean类型 用法 boolean resu ...

  8. 图文详解之ZSH美化你的终端CLI

    在这个博客中,我将介绍安装ITerm2,ZSH shell,“我的ZSH”,主题,ITerm2配色方案,“我的ZSH”插件,并启用“连线”支持,以帮助创建一个美丽而强大的终端. 如果你想让你的常规Ba ...

  9. flutter 解析json

    关于flutter 解析json 自己看了几天,最近才大概知道是怎么个情况. 首先 要处理的 是后端返回的数据 ,如果是直接请求的话返回的是json 字符串 然后要把字符串转成对象,有几种方式参考 第 ...

  10. 软件工程作业-(third)

    1.选题目(1) 最大连续子数组和(最大子段和) 问题:给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],-,a[n],求该序列如a[i]+a[i+1]+-+a[j]的子段和的最大值. ...