C# 託管窗口和單例窗口實現 NotifyIcon 與 user32.dll

注:案例是用WPF寫的,在winfrom 和 uwp 中應該也可以實現。

1.效果截圖:

2.新建一個WPF工程窗口。

3.雙擊MainWindow.xaml,設計窗口。

使用 ResizeMode="CanMinimize" 屬性值,禁止窗口最大化,這裏可以不禁用,看具體的需求。

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        ResizeMode="CanMinimize" 
        Title="MainWindow" Height="200" Width="750">
    <Grid>
        <Label Content="My Managed window" FontWeight="Bold" Foreground="Blue" FontSize="20px"  Margin="250,60"></Label>
    </Grid>
</Window>

4.給項目找個好看的圖標 .ico 和 .png 格式。

①新建資源文件,將上面兩張圖分別添加至資源文件當中。

②分別更改圖標資源屬性。

③更改窗口運行時標題欄和任務欄上的圖標;打開窗體屬性,選擇 .ico 圖標。

④更改程序exe圖標,選擇資源文件中的圖標。

⑤添加託管圖標 並且 在圖標上添加 雙擊事件,打開事件和 退出事件;另外添加單例窗口;代碼如下:

注:MainWindow.xaml.cs 中主要實現託管圖標,App.xaml.cs 中主要實現單例窗口。

MainWindow.xaml.cs 代碼:

using System;
using System.IO;
using System.Windows;
using System.Windows.Forms;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互邏輯
    /// </summary>
    public partial class MainWindow : Window
    {

        private NotifyIcon notifyIcon = null;

        public MainWindow()
        {
            InitializeComponent();

            //窗口顯示屏幕中間
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
           
            //重寫關閉事件
            Closing += Window_Closing;

            //託管圖標
            notifyIcon = new NotifyIcon
            {
                BalloonTipText = "My Managed Window",
                Text = "My Managed Window",
                Visible = true
            };

            Stream iconStream = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/WpfApplication1;component/Resources/Managed.ico")).Stream;
            notifyIcon.Icon = new System.Drawing.Icon(iconStream);
            notifyIcon.DoubleClick += NotifyIcon_DoubleClick;

            System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("打開");
            open.Click += Open_Click;
            System.Windows.Forms.MenuItem close = new System.Windows.Forms.MenuItem("退出");
            close.Click += Close_Click;
            System.Windows.Forms.MenuItem[] m = new System.Windows.Forms.MenuItem[] { open, close };
            notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(m);
        }

        /// <summary>
        /// 託管圖標,打開事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Open_Click(object sender, EventArgs e)
        {
            if (WindowState == WindowState.Minimized)
            {
                Show();
                WindowState = WindowState.Normal;
                ShowInTaskbar = true;
            }
            else
            {
                IntPtr hWnd = App.FindWindow(null, "My Managed Window");
                App.ShowWindow(hWnd, 9);
            }
        }

        /// <summary>
        /// 託管圖標,退出事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Close_Click(object sender, EventArgs e)
        {
            if (System.Windows.MessageBox.Show("是否確認退出?", "My Managed Window", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
            {
                Close();
                notifyIcon.Dispose();
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// 託管圖標,雙擊事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void NotifyIcon_DoubleClick(object sender, EventArgs e)
        {
            if (WindowState == WindowState.Minimized)
            {
                Show();
                WindowState = WindowState.Normal;
                ShowInTaskbar = true;
            }
            else
            {
                IntPtr hWnd = App.FindWindow(null, "My Managed Window");
                App.ShowWindow(hWnd, 9);
            }
        }

        /// <summary>
        /// 窗口關閉事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            IntPtr hWnd = App.FindWindow(null, "My Managed Window");
            App.ShowWindow(hWnd, 0);
            e.Cancel = true;
        }
    }
}

App.xaml.cs 代碼:

using System;
using System.Runtime.InteropServices;
using System.Windows;

namespace WpfApplication1
{
    /// <summary>
    /// App.xaml 的交互邏輯
    /// </summary>
    public partial class App : Application
    {
        [DllImport("USER32.DLL", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        public static extern IntPtr FindWindow(string classname, string captionName);

        [DllImport("USER32.DLL")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("USER32.DLL")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        public System.Threading.Mutex mutex;
        public App()
        {
            this.Startup += new StartupEventHandler(App_Startup);
        }

        /// <summary>
        /// 單例窗口,防止用戶打開多個窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void App_Startup(object sender, StartupEventArgs e)
        {
            try
            {
                bool ret;
                mutex = new System.Threading.Mutex(true, "My Managed Window", out ret);
                if (!ret)
                {
                    IntPtr hWnd = FindWindow(null, "My Managed Window");
                    ShowWindow(hWnd, 9);
                    SetForegroundWindow(hWnd);
                    Environment.Exit(0);
                }
            }
            catch (Exception /*ex*/)
            {
                Environment.Exit(0);
            }
        }

    }
}

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章