RunMode.cs 6.5 KB
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;

namespace BLL
{
    public static class RunMode
    {
        [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
        private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
        [DllImport("user32.dll ", SetLastError = true)]
        private static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
        private const int SW_RESTORE = 9;

        private static Form frm;
        private static FormWindowState state;
        private static bool exit = false;
        private static ToolStripItem[] items;
        private static NotifyIcon notify;
        private static ContextMenuStrip notifyMenu;


        private static void AddItem()
        {
            notifyMenu = new ContextMenuStrip();
            items = new ToolStripItem[4];

            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetEntryAssembly();
            string text = assembly.GetName().Version.ToString();
            text = frm.Text + (frm.Text.Contains(text) ? "" : "  " + text);

            items[0] = new ToolStripMenuItem(text) { Font = new Font("微软雅黑", 11f, FontStyle.Bold), Image = frm.Icon.ToBitmap() };
            items[1] = new ToolStripSeparator();
            items[2] = new ToolStripMenuItem("显示") { Font = new Font("微软雅黑", 11f) };
            items[3] = new ToolStripMenuItem("退出") { Font = new Font("微软雅黑", 11f) };
            notifyMenu.Items.AddRange(items);

            items[2].Click += ItemShow_Click;
            items[3].Click += ItemExit_Click;

            notify = new NotifyIcon { Icon = frm.Icon, Visible = true, ContextMenuStrip = notifyMenu, Text = frm.Text };
            notify.MouseDoubleClick += Notify_MouseDoubleClick;
        }

        private static void ItemShow_Click(object sender, EventArgs e)
        {
            frm.Show();
            if (frm.WindowState == FormWindowState.Minimized)
                frm.WindowState = state;
        }

        private static void ItemExit_Click(object sender, EventArgs e)
        {
            notify.Dispose();
            exit = true;
            frm.Close();
        }

        private static void Notify_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            frm.Show();
            if (frm.WindowState == FormWindowState.Minimized)
                frm.WindowState = state;
        }




        public static void Init(Form frm)
        {
            RunMode.frm = frm;
            state = frm.WindowState;
            frm.StartPosition = FormStartPosition.CenterScreen;
            AddItem();
        }

        public static void MenuLanguage(params string[] name)
        {
            if (items == null || name == null) return;
            if (name.Length >= 1) items[2].Text = name[0];
            if (name.Length >= 2) items[3].Text = name[1];
        }

        public static bool Closing(FormClosingEventArgs e)
        {
            if (!exit)
            {
                e.Cancel = true;
                state = frm.WindowState;
                frm.WindowState = FormWindowState.Minimized;
            }
            return exit;
        }

        public static bool IsRun()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id == current.Id) continue;  //自己
                if (process.MainModule.FileName == current.MainModule.FileName)
                {
                    //显示已打开的程序
                    ShowWindow(process.MainWindowHandle, SW_RESTORE);
                    SwitchToThisWindow(process.MainWindowHandle, true);
                    return true;
                }
            }
            return false;
        }

        public static bool IsAdmin()
        {
            System.Security.Principal.WindowsIdentity current = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(current);
            return windowsPrincipal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
        }

        public static void AdminRun()
        {
            string path = Process.GetCurrentProcess().MainModule.FileName;
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                UseShellExecute = true,
                WorkingDirectory = Environment.CurrentDirectory,
                FileName = path,
                Verb = "runas"
            };
            Process.Start(startInfo);
        }

        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="srcPath">原路径</param>
        /// <param name="dstPath">目标路径</param>
        /// <param name="overwrite">是否覆盖</param>
        /// <returns></returns>
        //public static bool CopyFile(string srcPath, string dstPath, bool overwrite)
        //{
        //    bool rtn = false;
        //    try
        //    {
        //        if (!srcPath.EndsWith("\\")) srcPath += "\\";
        //        if (!dstPath.EndsWith("\\")) dstPath += "\\";

        //        if (System.IO.Directory.Exists(srcPath))
        //        {
        //            //目录是否存在
        //            if (!System.IO.Directory.Exists(dstPath))
        //                System.IO.Directory.CreateDirectory(dstPath);

        //            //复制文件
        //            string[] files = System.IO.Directory.GetFiles(srcPath);
        //            foreach (string file in files)
        //            {
        //                System.IO.FileInfo fInfo = new System.IO.FileInfo(file);
        //                fInfo.CopyTo(dstPath + fInfo.Name, overwrite);
        //            }
        //            rtn = true;

        //            //复制文件夹
        //            string[] dirs = System.IO.Directory.GetDirectories(srcPath);
        //            foreach (string dir in dirs)
        //            {
        //                System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(dir);
        //                rtn = CopyFile(dir, dstPath + dInfo.Name, overwrite);
        //                if (!rtn) break;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        rtn = false;
        //    }
        //    return rtn;
        //}















    }

}