欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WPF实现只打开一个窗口,并且重复打开时已经打开的窗口置顶

程序员文章站 2022-03-25 18:49:07
内容来自:https://codereview.stackexchange.com/questions/20871/single-instance-wpf-application 第一步:添加System.RunTime.Remoting引用 第二步:新建一个类class1.cs(按自己想法命名) ......

内容来自: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 = 0;

                argv = _commandlinetoargvw(cmdline, out numargs);
                if (argv == intptr.zero)
                {
                    throw new win32exception();
                }
                var result = new string[numargs];

                for (int i = 0; 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