WinForm 无边框窗体四周阴影 窗体可拖动 无边框自定义标题栏

  • Post author:
  • Post category:其他


● 开发环境



Microsoft Visual Studio

● 开发语言



Visual C#

● 开发过程

1、新建一个


Windows窗体应用(.NET Framework)


,项目名称为


MyApp


,确定生成解决方案。

2、在解决方案资源管理器里将Form1更改为FormMain。

3、在解决方案资源管理器里右击解决方案’MyApp’,


添加-新建项目-类库(.NET Framework)


,项目名称为


Framework


,确定添加项目。



Framework项目

4、将默认的Class1.cs更改为Framework.cs;

在Framework项目上

右键-添加-Windows窗体

,名称为

FormSkin.cs

;再添加一个

Windows窗体

,名称为

FormMain.cs


5、准备一张四周边缘透明的位图,添加到Resources.resx。

6、双击FormSkin.cs,打开窗体设计器,

将FormSkin的

FormBorderStyle

更改为

None

,MaximizeBox更改为False,MinimizeBox更改为False,Size更改为800,450,StartPosition更改为CenterScreen。

7、双击FormMain.cs,打开窗体设计器,

将FormMain的

FormBorderStyle

更改为

None

,MaximizeBox更改为False,MinimizeBox更改为False,Size更改为800,450,StartPosition更改为CenterScreen。

8、打开Framework.cs代码编辑器,添加如下代码:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;

namespace Framework
{
    public static class GraphicsPathHelper
    {
        public static GraphicsPath CreatePath(Rectangle rect, int radius, RoundStyle style, bool correction)
        {
            GraphicsPath path = new GraphicsPath();
            int radiusCorrection = correction ? 1 : 0;
            switch (style)
            {
                case RoundStyle.None:
                    path.AddRectangle(rect);
                    break;
                case RoundStyle.All:
                    path.AddArc(rect.X, rect.Y, radius, radius, 180, 90);
                    path.AddArc(rect.Right - radius - radiusCorrection, rect.Y, radius, radius, 270, 90);
                    path.AddArc(rect.Right - radius - radiusCorrection, rect.Bottom - radius - radiusCorrection, radius, radius, 0, 90);
                    path.AddArc(rect.X, rect.Bottom - radius - radiusCorrection, radius, radius, 90, 90);
                    break;
                case RoundStyle.Left:
                    path.AddArc(rect.X, rect.Y, radius, radius, 180, 90);
                    path.AddLine(rect.Right - radiusCorrection, rect.Y, rect.Right - radiusCorrection, rect.Bottom - radiusCorrection);
                    path.AddArc(rect.X, rect.Bottom - radius - radiusCorrection, radius, radius, 90, 90);
                    break;
                case RoundStyle.Right:
                    path.AddArc(rect.Right - radius - radiusCorrection, rect.Y, radius, radius, 270, 90);
                    path.AddArc(rect.Right - radius - radiusCorrection, rect.Bottom - radius - radiusCorrection, radius, radius, 0, 90);
                    path.AddLine(rect.X, rect.Bottom - radiusCorrection, rect.X, rect.Y);
                    break;
                case RoundStyle.Top:
                    path.AddArc(rect.X, rect.Y, radius, radius, 180, 90);
                    path.AddArc(rect.Right - radius - radiusCorrection, rect.Y, radius, radius, 270, 90);
                    path.AddLine(rect.Right - radiusCorrection, rect.Bottom - radiusCorrection, rect.X, rect.Bottom - radiusCorrection);
                    break;
                case RoundStyle.Bottom:
                    path.AddArc(rect.Right - radius - radiusCorrection, rect.Bottom - radius - radiusCorrection, radius, radius, 0, 90);
                    path.AddArc(rect.X, rect.Bottom - radius - radiusCorrection, radius, radius, 90, 90);
                    path.AddLine(rect.X, rect.Y, rect.Right - radiusCorrection, rect.Y);
                    break;
                case RoundStyle.BottomLeft:
                    path.AddArc(rect.X, rect.Bottom - radius - radiusCorrection, radius, radius, 90, 90);
                    path.AddLine(rect.X, rect.Y, rect.Right - radiusCorrection, rect.Y);
                    path.AddLine(rect.Right - radiusCorrection, rect.Y, rect.Right - radiusCorrection, rect.Bottom - radiusCorrection);
                    break;
                case RoundStyle.BottomRight:
                    path.AddArc(rect.Right - radius - radiusCorrection, rect.Bottom - radius - radiusCorrection, radius, radius, 0, 90);
                    path.AddLine(rect.X, rect.Bottom - radiusCorrection, rect.X, rect.Y);
                    path.AddLine(rect.X, rect.Y, rect.Right - radiusCorrection, rect.Y);
                    break;
            }
            path.CloseFigure();
            return path;
        }
    }

    public enum RoundStyle
    {
        /// <summary>
        /// 四个角都不是圆角
        /// </summary>
        None = 0,
        /// <summary>
        /// 四个角都为圆角
        /// </summary>
        All = 1,
        /// <summary>
        /// 左边两个为圆角
        /// </summary>
        Left = 2,
        /// <summary>
        /// 右边两个为圆角
        /// </summary>
        Right = 3,
        /// <summary>
        /// 上边两个为圆角
        /// </summary>
        Top = 4,
        /// <summary>
        /// 下边两个为圆角
        /// </summary>
        Bottom = 5,
        /// <summary>
        /// 左下角为圆角
        /// </summary>
        BottomLeft = 6,
        /// <summary>
        /// 右下角为圆角
        /// </summary>
        BottomRight = 7,
    }

    public partial class ImageDrawRect
    {
        public static ContentAlignment anyRight = ContentAlignment.BottomRight | (ContentAlignment.MiddleRight | ContentAlignment.TopRight);
        public static ContentAlignment anyTop = ContentAlignment.TopRight | (ContentAlignment.TopCenter | ContentAlignment.TopLeft);
        public static ContentAlignment anyBottom = ContentAlignment.BottomRight | (ContentAlignment.BottomCenter | ContentAlignment.BottomLeft);
        public static ContentAlignment anyCenter = ContentAlignment.BottomCenter | (ContentAlignment.MiddleCenter | ContentAlignment.TopCenter);
        public static ContentAlignment anyMiddle = ContentAlignment.MiddleRight | (ContentAlignment.MiddleCenter | ContentAlignment.MiddleLeft);

        public static void DrawRect(Graphics g, Bitmap img, Rectangle r, Rectangle lr, int index, int Totalindex)
        {
            if (img == null) return;
            Rectangle r1, r2;
            int x = (index - 1) * img.Width / Totalindex;
            int y = 0;
            int x1 = r.Left;
            int y1 = r.Top;

            if (r.Height > img.Height && r.Width <= img.Width / Totalindex)
            {
                r1 = new Rectangle(x, y, img.Width / Totalindex, lr.Top);
                r2 = new Rectangle(x1, y1, r.Width, lr.Top);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x, y + lr.Top, img.Width / Totalindex, img.Height - lr.Top - lr.Bottom);
                r2 = new Rectangle(x1, y1 + lr.Top, r.Width, r.Height - lr.Top - lr.Bottom);
                if ((lr.Top + lr.Bottom) == 0) r1.Height -= 1;
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x, y + img.Height - lr.Bottom, img.Width / Totalindex, lr.Bottom);
                r2 = new Rectangle(x1, y1 + r.Height - lr.Bottom, r.Width, lr.Bottom);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);
            }
            else if (r.Height <= img.Height && r.Width > img.Width / Totalindex)
            {
                r1 = new Rectangle(x, y, lr.Left, img.Height);
                r2 = new Rectangle(x1, y1, lr.Left, r.Height);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);
                r1 = new Rectangle(x + lr.Left, y, img.Width / Totalindex - lr.Left - lr.Right, img.Height);
                r2 = new Rectangle(x1 + lr.Left, y1, r.Width - lr.Left - lr.Right, r.Height);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);
                r1 = new Rectangle(x + img.Width / Totalindex - lr.Right, y, lr.Right, img.Height);
                r2 = new Rectangle(x1 + r.Width - lr.Right, y1, lr.Right, r.Height);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);
            }
            else if (r.Height <= img.Height && r.Width <= img.Width / Totalindex)
            {
                r1 = new Rectangle((index - 1) * img.Width / Totalindex, 0, img.Width / Totalindex, img.Height - 1);
                g.DrawImage(img, new Rectangle(x1, y1, r.Width, r.Height), r1, GraphicsUnit.Pixel);
            }
            else if (r.Height > img.Height && r.Width > img.Width / Totalindex)
            {
                r1 = new Rectangle(x, y, lr.Left, lr.Top);
                r2 = new Rectangle(x1, y1, lr.Left, lr.Top);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x, y + img.Height - lr.Bottom, lr.Left, lr.Bottom);
                r2 = new Rectangle(x1, y1 + r.Height - lr.Bottom, lr.Left, lr.Bottom);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x, y + lr.Top, lr.Left, img.Height - lr.Top - lr.Bottom);
                r2 = new Rectangle(x1, y1 + lr.Top, lr.Left, r.Height - lr.Top - lr.Bottom);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x + lr.Left, y, img.Width / Totalindex - lr.Left - lr.Right, lr.Top);
                r2 = new Rectangle(x1 + lr.Left, y1, r.Width - lr.Left - lr.Right, lr.Top);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x + img.Width / Totalindex - lr.Right, y, lr.Right, lr.Top);
                r2 = new Rectangle(x1 + r.Width - lr.Right, y1, lr.Right, lr.Top);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x + img.Width / Totalindex - lr.Right, y + lr.Top, lr.Right, img.Height - lr.Top - lr.Bottom);
                r2 = new Rectangle(x1 + r.Width - lr.Right, y1 + lr.Top, lr.Right, r.Height - lr.Top - lr.Bottom);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x + img.Width / Totalindex - lr.Right, y + img.Height - lr.Bottom, lr.Right, lr.Bottom);
                r2 = new Rectangle(x1 + r.Width - lr.Right, y1 + r.Height - lr.Bottom, lr.Right, lr.Bottom);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x + lr.Left, y + img.Height - lr.Bottom, img.Width / Totalindex - lr.Left - lr.Right, lr.Bottom);
                r2 = new Rectangle(x1 + lr.Left, y1 + r.Height - lr.Bottom, r.Width - lr.Left - lr.Right, lr.Bottom);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);

                r1 = new Rectangle(x + lr.Left, y + lr.Top, img.Width / Totalindex - lr.Left - lr.Right, img.Height - lr.Top - lr.Bottom);
                r2 = new Rectangle(x1 + lr.Left, y1 + lr.Top, r.Width - lr.Left - lr.Right, r.Height - lr.Top - lr.Bottom);
                g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);
            }
        }

        public static void DrawRect(Graphics g, Bitmap img, Rectangle r, int index, int Totalindex)
        {
            if (img == null) return;
            int width = img.Width / Totalindex;
            int height = img.Height;
            Rectangle r1, r2;
            int x = (index - 1) * width;
            int y = 0;
            int x1 = r.Left;
            int y1 = r.Top;
            r1 = new Rectangle(x, y, width, height);
            r2 = new Rectangle(x1, y1, r.Width, r.Height);
            g.DrawImage(img, r2, r1, GraphicsUnit.Pixel);
        }

        public static Rectangle HAlignWithin(Size alignThis, Rectangle withinThis, ContentAlignment align)
        {
            if ((align & anyRight) != (ContentAlignment)0)
            {
                withinThis.X += (withinThis.Width - alignThis.Width);
            }
            else if ((align & anyCenter) != ((ContentAlignment)0))
            {
                withinThis.X += ((withinThis.Width - alignThis.Width + 1) / 2);
            }
            withinThis.Width = alignThis.Width;
            return withinThis;
        }

        public static Rectangle VAlignWithin(Size alignThis, Rectangle withinThis, ContentAlignment align)
        {
            if ((align & anyBottom) != ((ContentAlignment)0))
            {
                withinThis.Y += (withinThis.Height - alignThis.Height);
            }
            else if ((align & anyMiddle) != ((ContentAlignment)0))
            {
                withinThis.Y += ((withinThis.Height - alignThis.Height + 1) / 2);
            }
            withinThis.Height = alignThis.Height;
            return withinThis;
        }
    }
    public class Win32
    {
        public const int GWL_EXSTYLE = -20;
        public const int WS_EX_TRANSPARENT = 0x00000020;
        public const int WS_EX_LAYERED = 0x00080000;

        [StructLayout(LayoutKind.Sequential)]
        public struct Size
        {
            public Int32 cx;
            public Int32 cy;

            public Size(Int32 x, Int32 y)
            {
                cx = x;
                cy = y;
            }
        }

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct BLENDFUNCTION
        {
            public byte BlendOp;
            public byte BlendFlags;
            public byte SourceConstantAlpha;
            public byte AlphaFormat;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct Point
        {
            public Int32 x;
            public Int32 y;

            public Point(Int32 x, Int32 y)
            {
                this.x = x;
                this.y = y;
            }
        }

        public const byte AC_SRC_OVER = 0;

        public const Int32 ULW_ALPHA = 2;

        public const byte AC_SRC_ALPHA = 1;

        public const Int32 AW_HOR_POSITIVE = 0x00000001;

        public const Int32 AW_HOR_NEGATIVE = 0x00000002;

        public const Int32 AW_VER_POSITIVE = 0x00000004;

        public const Int32 AW_VER_NEGATIVE = 0x00000008;

        public const Int32 AW_CENTER = 0x00000010;

        public const Int32 AW_HIDE = 0x00010000;

        public const Int32 AW_ACTIVATE = 0x00020000;

        public const Int32 AW_SLIDE = 0x00040000;

        public const Int32 AW_BLEND = 0x00080000;

        [DllImport("user32")]
        public static extern bool AnimateWindow(IntPtr whnd, int dwtime, int dwflag);

        [DllImport("user32", EntryPoint = "GetWindowLong")]
        public static extern int GetWindowLong(IntPtr hwnd, int nIndex);

        [DllImport("user32.dll")]
        public static extern int SetWindowLong(IntPtr hwnd, int nIndex, int dwNewLong);

        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDC);

        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern IntPtr GetDC(IntPtr hWnd);

        [DllImport("gdi32.dll", ExactSpelling = true)]
        public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObj);

        [DllImport("user32.dll", ExactSpelling = true)]
        public static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern int DeleteDC(IntPtr hDC);

        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern int DeleteObject(IntPtr hObj);

        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
        public static extern int UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, ref Size psize, IntPtr hdcSrc, ref Point pptSrc, Int32 crKey, ref BLENDFUNCTION pblend, Int32 dwFlags);

    }
}

9、打开FormSkin.cs代码编辑器,添加如下代码:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace Framework
{
    public partial class FormSkin : Form
    {
        public FormSkin()
        {
            InitializeComponent();
        }

        //控件层
        private readonly FormMain formMain;
        #region 带参构造
        public FormSkin(FormMain main)
        {
            //将控制层传值过来
            formMain = main;
            InitializeComponent();
            //置顶窗体
            formMain.TopMost = TopMost
            formMain.BringToFront();
            //是否在任务栏显示
            ShowInTaskbar = false;
            //无边框模式
            FormBorderStyle = FormBorderStyle.None;
            //设置绘图层显示位置
            Location = new Point(formMain.Location.X - 5, formMain.Location.Y - 5);
            //设置ICO
            Icon = formMain.Icon;
            ShowIcon = formMain.ShowIcon;
            //设置大小
            Width = formMain.Width + 10;
            Height = formMain.Height + 10;
            //设置标题名
            Text = formMain.Text;
            //绘图层窗体移动
            formMain.LocationChanged += new EventHandler(Main_LocationChanged);
            formMain.SizeChanged += new EventHandler(Main_SizeChanged);
            formMain.VisibleChanged += new EventHandler(Main_VisibleChanged);
            //加载背景
            SetBits();
            //窗口鼠标穿透效果
            CanPenetrate();
        }

        #endregion

        #region 还原任务栏右键菜单
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cParms = base.CreateParams;
                cParms.ExStyle |= 0x00080000; // WS_EX_LAYERED
                return cParms;
            }
        }
        #endregion

        #region 控件层相关事件
        //移动主窗体时
        void Main_LocationChanged(object sender, EventArgs e)
        {
            Location = new Point(formMain.Left - 5, formMain.Top - 5);
        }

        //主窗体大小改变时
        void Main_SizeChanged(object sender, EventArgs e)
        {
            //设置大小
            Width = formMain.Width + 10;
            Height = formMain.Height + 10;
            SetBits();
        }

        //主窗体显示或隐藏时
        void Main_VisibleChanged(object sender, EventArgs e)
        {
            Visible = formMain.Visible;
        }
        #endregion

        #region 使窗口有鼠标穿透功能
        /// <summary>
        /// 使窗口有鼠标穿透功能
        /// </summary>
        private void CanPenetrate()
        {
            Win32.GetWindowLong(Handle, Win32.GWL_EXSTYLE);
            Win32.SetWindowLong(Handle, Win32.GWL_EXSTYLE, Win32.WS_EX_TRANSPARENT | Win32.WS_EX_LAYERED);
        }
        #endregion

        #region 不规则无毛边方法
        public void SetBits()
        {
            //绘制绘图层背景
            Bitmap bitmap = new Bitmap(formMain.Width + 10, formMain.Height + 10);
            Rectangle _BacklightLTRB = new Rectangle(20, 20, 20, 20);//窗体光泽重绘边界
            Graphics g = Graphics.FromImage(bitmap);
            g.SmoothingMode = SmoothingMode.HighQuality; //高质量
            g.PixelOffsetMode = PixelOffsetMode.HighQuality; //高像素偏移质量
            ImageDrawRect.DrawRect(g, Properties.Resources.bkg, ClientRectangle, Rectangle.FromLTRB(_BacklightLTRB.X, _BacklightLTRB.Y, _BacklightLTRB.Width, _BacklightLTRB.Height), 1, 1);

            if (!Image.IsCanonicalPixelFormat(bitmap.PixelFormat) || !Image.IsAlphaPixelFormat(bitmap.PixelFormat))
                throw new ApplicationException("图片必须是32位带Alhpa通道的图片。");
            IntPtr oldBits = IntPtr.Zero;
            IntPtr screenDC = Win32.GetDC(IntPtr.Zero);
            IntPtr hBitmap = IntPtr.Zero;
            IntPtr memDc = Win32.CreateCompatibleDC(screenDC);

            try
            {
                Win32.Point topLoc = new Win32.Point(Left, Top);
                Win32.Size bitMapSize = new Win32.Size(Width, Height);
                Win32.BLENDFUNCTION blendFunc = new Win32.BLENDFUNCTION();
                Win32.Point srcLoc = new Win32.Point(0, 0);

                hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
                oldBits = Win32.SelectObject(memDc, hBitmap);

                blendFunc.BlendOp = Win32.AC_SRC_OVER;
                blendFunc.SourceConstantAlpha = byte.Parse("255");
                blendFunc.AlphaFormat = Win32.AC_SRC_ALPHA;
                blendFunc.BlendFlags = 0;

                Win32.UpdateLayeredWindow(Handle, screenDC, ref topLoc, ref bitMapSize, memDc, ref srcLoc, 0, ref blendFunc, Win32.ULW_ALPHA);
            }
            finally
            {
                if (hBitmap != IntPtr.Zero)
                {
                    Win32.SelectObject(memDc, oldBits);
                    Win32.DeleteObject(hBitmap);
                }
                Win32.ReleaseDC(IntPtr.Zero, screenDC);
                Win32.DeleteDC(memDc);
            }
        }
        #endregion
    }
}

10、打开FormMain.cs代码编辑器,添加如下代码:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace Framework
{

    public partial class FormMain : Form
    {
        //绘制层
        private FormSkin formSkin;
        public FormMain()
        {
            InitializeComponent();
            SetStyles();
        }
        #region 减少闪烁
        private void SetStyles()
        {
            SetStyle(
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.OptimizedDoubleBuffer |
                ControlStyles.ResizeRedraw |
                ControlStyles.DoubleBuffer, true);
            //强制分配样式重新应用到控件上
            UpdateStyles();
            AutoScaleMode = AutoScaleMode.None;
        }
        #endregion

        //#region 变量属性
        不显示FormBorderStyle属性
        //[Browsable(false)]
        //[EditorBrowsable(EditorBrowsableState.Never)]
        //[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        //public new FormBorderStyle FormBorderStyle
        //{
        //    get { return base.FormBorderStyle; }
        //    set { base.FormBorderStyle = FormBorderStyle.None; }
        //}
        //#endregion

        #region 重载事件
        //Show或Hide被调用时
        protected override void OnVisibleChanged(EventArgs e)
        {
            if (Visible)
            {
                //启用窗口淡入淡出
                if (!DesignMode)
                {
                    //淡入特效
                    Win32.AnimateWindow(Handle, 150, Win32.AW_BLEND | Win32.AW_ACTIVATE);
                }
                //判断不是在设计器中
                if (!DesignMode && formSkin == null)
                {
                    formSkin = new FormSkin(this);
                    formSkin.Show(this);
                }
                base.OnVisibleChanged(e);
            }
            else
            {
                base.OnVisibleChanged(e);
                Win32.AnimateWindow(Handle, 150, Win32.AW_BLEND | Win32.AW_HIDE);
            }
        }

        //窗体关闭时
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            //先关闭阴影窗体
            if (formSkin != null)
            {
                formSkin.Close();
            }
            //在Form_FormClosing中添加代码实现窗体的淡出
            Win32.AnimateWindow(Handle, 150, Win32.AW_BLEND | Win32.AW_HIDE);
        }

        //控件首次创建时被调用
        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            SetReion();
        }

        //圆角
        private void SetReion()
        {
            using (GraphicsPath path =
                    GraphicsPathHelper.CreatePath(
                    new Rectangle(Point.Empty, Size), 5, RoundStyle.None, true))
            {
                Region region = new Region(path);
                path.Widen(Pens.White);
                region.Union(path);
                Region = region;
            }
        }

        //改变窗体大小时
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            SetReion();
        }

        const int HTLEFT = 10;
        const int HTRIGHT = 11;
        const int HTTOP = 12;
        const int HTTOPLEFT = 13;
        const int HTTOPRIGHT = 14;
        const int HTBOTTOM = 15;
        const int HTBOTTOMLEFT = 0x10;
        const int HTBOTTOMRIGHT = 17;
        const int WM_NCHITTEST = 0x084;

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_NCHITTEST://移动鼠标,按住或释放鼠标时发生
                    //窗体为窗口模式/普通默认(非全屏)
                    if (WindowState == FormWindowState.Normal)
                    {
                        base.WndProc(ref m);
                        Point vPoint = new Point((int)m.LParam & 0xFFFF,
                        (int)m.LParam >> 16 & 0xFFFF);
                        vPoint = PointToClient(vPoint);
                        if (vPoint.X <= 5)
                            if (vPoint.Y <= 5)
                                m.Result = (IntPtr)HTTOPLEFT;
                            else if (vPoint.Y >= ClientSize.Height - 5)
                                m.Result = (IntPtr)HTBOTTOMLEFT;
                            else m.Result = (IntPtr)HTLEFT;
                        else if (vPoint.X >= ClientSize.Width - 5)
                            if (vPoint.Y <= 5)
                                m.Result = (IntPtr)HTTOPRIGHT;
                            else if (vPoint.Y >= ClientSize.Height - 5)
                                m.Result = (IntPtr)HTBOTTOMRIGHT;
                            else m.Result = (IntPtr)HTRIGHT;
                        else if (vPoint.Y <= 5)
                            m.Result = (IntPtr)HTTOP;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)HTBOTTOM;
                        break;
                    }
                    //窗体非正常模式大小(全屏)
                    else
                    {
                        break;
                    }
                case 0x0201://鼠标左键按下的消息 
                    m.Msg = 0x00A1;//更改消息为非客户区按下鼠标 
                    m.LParam = IntPtr.Zero;//默认值 
                    m.WParam = new IntPtr(2);//鼠标放在标题栏内 
                    base.WndProc(ref m);
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }
        #endregion

        #region 允许点击任务栏最小化
        protected override CreateParams CreateParams
        {
            get
            {
                const int WS_MINIMIZEBOX = 0x00020000;  // Winuser.h中定义
                CreateParams cp = base.CreateParams;
                cp.Style |= WS_MINIMIZEBOX;   // 允许最小化操作
                return cp;
            }
        }
        #endregion
    }
}



MyApp项目

11、在MyApp项目引用上右键-添加引用-项目-勾选Framework-确定。

12、双击FormMain.cs,打开窗体设计器,添加3个Panel控件,分别为PanelTitle(标题栏[非客户区]),PanelWindow(主容器[客户区]),PanelStatusBar(状态栏[非客户区]);在PanelTitle里添加5个PictureBox控件,分别为PictureBoxIcon(应用程序图标),PictureBoxCloseWindow(关闭按钮),PictureBoxMinimizeBox(最小化按钮),PictureBoxMaximizeBox(最大化按钮),PictureBoxRestoreWindow(向下还原按钮)……

13、在MyApp项目上右键-添加-类,名称为Common.cs,添加如下代码:

using System;
using System.Management;

namespace MyApp
{
    #region 操作系统
    public class OSInformation
    {
        /// <summary>
        /// 获取操作系统信息
        /// </summary>
        /// <returns>操作系统完整版本信息</returns>
        public static string GetOSFullVersion()
        {
            string strOS = string.Empty;
            string strBuild = string.Empty;

            //【1】获取操作系统
            SelectQuery query = new SelectQuery("Win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection collection = searcher.Get();
            searcher.Dispose();
            foreach (ManagementObject obj in collection)
            {
                strOS = obj.GetPropertyValue("Caption").ToString().Replace("Microsoft", "");//返回(Microsoft)Windows 10 专业版
            }

            string strBit;
            //【2】判断系统32位还是64位
            if (Environment.Is64BitOperatingSystem) strBit = "64位";
            else strBit = "32位";

            string strSP;
            //【3】获取补丁包版本号
            if (Environment.OSVersion.Version.Major != 10)
            {
                strSP = " " + Environment.OSVersion.ServicePack;
            }
            else
            {
                strSP = Environment.OSVersion.ServicePack;
            }

            //【4】获取操作系统版本
            string strVersion = Environment.OSVersion.Version.Major + "." + Environment.OSVersion.Version.Minor;

            //【5】获取系统内部版本
            foreach (ManagementObject obj in collection)
            {
                strBuild = obj.GetPropertyValue("BuildNumber").ToString();
            }
            
            //【6】组合操作系统完整版本
            return strOS + " " + strBit + strSP + "(" + strVersion + ",版本 " + strBuild + ")";
        }
    }
    #endregion

    #region 日期时间
    public class DateInformation
    {
        #region 日期时间
        /// <summary>
        /// 获取系统当前日期时间
        /// </summary>
        /// <returns>当前日期和时间</returns>
        public static string GetSystemDateTime()
        {
            return DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
        }

        /// <summary>
        /// 获取星期
        /// </summary>
        /// <returns>星期</returns>
        public static string GetDayOfWeek()
        {
            string[] strWeekDay = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            return strWeekDay[Convert.ToInt32(DateTime.Now.DayOfWeek)];
        }

        /// <summary>
        /// 获取一年中的第多少天
        /// </summary>
        /// <returns>一年中的第多少天</returns>
        public static string GetDayOfYear()
        {
            return "第" + DateTime.Now.DayOfYear + "天";
        }

        /// <summary>
        /// 获取系统已运行时间
        /// </summary>
        /// <returns>系统已运行时间</returns>
        public static string GetSystemRunTime()
        {
            long nCurTickValue = Environment.TickCount;
            long nRunHours, nRunMinutes, nRunSeconds;
            nRunHours = (nCurTickValue / (3600 * 999)) % 24;
            nRunMinutes = (nCurTickValue / (60 * 999)) % 60;
            nRunSeconds = (nCurTickValue / 999) % 60;
            return string.Format("{0}小时{1}分钟{2}秒钟", nRunHours.ToString("00"), nRunMinutes.ToString("00"), nRunSeconds.ToString("00"));
        }
        #endregion

        #region 获取中国农历信息
        /// <summary>
        /// 实例化农历类
        /// </summary>
        private static readonly System.Globalization.ChineseLunisolarCalendar chslc = new System.Globalization.ChineseLunisolarCalendar();
        /// <summary>
        /// 十天干
        /// </summary>
        private static readonly string[] tg = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" };
        /// <summary>
        /// 十二地支
        /// </summary>
        private static readonly string[] dz = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" };
        /// <summary>
        /// 十二生肖
        /// </summary>
        private static readonly string[] sx = { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" };

        /// <summary>
        /// 返回农历天干地支年
        /// </summary>
        /// <param name="year">农历年</param>
        /// <returns></returns>
        private static string GetLunisolarYear(int year)
        {
            if (year > 3)
            {
                int tgIndex = (year - 4) % 10;
                int dzIndex = (year - 4) % 12;
                return string.Concat(tg[tgIndex], dz[dzIndex], "[", sx[dzIndex], "]");
            }
            throw new ArgumentOutOfRangeException("无效的年份!");
        }

        /// <summary>
        /// 农历月
        /// </summary>
        private static readonly string[] months = { "正", "二", "三", "四", "五", "六", "七", "八", "九", "十", "冬", "腊" };

        /// <summary>
        /// 农历日第一字
        /// </summary>
        private static readonly string[] days1 = { "初", "十", "廿", "三" };

        /// <summary>
        /// 农历日第二字
        /// </summary>
        private static readonly string[] days2 = { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十" };

        /// <summary>
        /// 返回农历月
        /// </summary>
        /// <param name="month">月份</param>
        /// <returns></returns>
        private static string GetLunisolarMonth(int month)
        {
            if (month < 13 && month > 0)
            {
                return months[month - 1];
            }
            throw new ArgumentOutOfRangeException("无效的月份!");
        }

        /// <summary>
        /// 返回农历日
        /// </summary>
        /// <param name="day">日期</param>
        /// <returns></returns>
        private static string GetLunisolarDay(int day)
        {
            if (day > 0 && day < 32)
            {
                if (day != 20 && day != 30)
                {
                    return string.Concat(days1[(day - 1) / 10], days2[(day - 1) % 10]);
                }
                else
                {
                    return string.Concat(days2[(day - 1) / 10], days1[1]);
                }
            }
            throw new ArgumentOutOfRangeException("无效的日期!");
        }

        /// <summary>
        /// 获取完整农历(包含年月日)
        /// </summary>
        /// <returns>完整农历</returns>
        public static string GetChineseLunisolarCalendar()
        {
            int year = chslc.GetYear(DateTime.Now);
            int month = chslc.GetMonth(DateTime.Now);
            int day = chslc.GetDayOfMonth(DateTime.Now);
            int leapMonth = chslc.GetLeapMonth(year);
            bool isleap = false;
            if (leapMonth > 0)
            {
                if (leapMonth == month)
                {
                    isleap = true;
                    month--;
                }
                else if (month > leapMonth)
                {
                    month--;
                }
            }
            return GetLunisolarYear(year) + "年" + (isleap ? "闰" : string.Empty) + GetLunisolarMonth(month) + "月" + GetLunisolarDay(day);
        }

        /// <summary>
        /// 获取农历日期(月日)
        /// </summary>
        /// <returns>农历日期</returns>
        public static string GetChineseLunisolarDate()
        {
            int year = chslc.GetYear(DateTime.Now);
            int month = chslc.GetMonth(DateTime.Now);
            int day = chslc.GetDayOfMonth(DateTime.Now);
            int leapMonth = chslc.GetLeapMonth(year);
            bool isleap = false;
            if (leapMonth > 0)
            {
                if (leapMonth == month)
                {
                    isleap = true;
                    month--;
                }
                else if (month > leapMonth)
                {
                    month--;
                }
            }
            return (isleap ? "闰" : string.Empty) + GetLunisolarMonth(month) + "月" + GetLunisolarDay(day);
        }
        #endregion

        #region 中国节日信息
        /// <summary>
        /// 获取中国节日信息
        /// </summary>
        /// <returns>中国节日</returns>
        public static string GetChineseFestival()
        {
            string ChineseLunisolarDate = GetChineseLunisolarDate();
            #region 农历节日
            if (ChineseLunisolarDate == "正月初一" || ChineseLunisolarDate == "闰正月初一")
            {
                return "春节";
            }
            else if (ChineseLunisolarDate == "正月十五" || ChineseLunisolarDate == "闰正月十五")
            {
                return "元宵节/上元节";
            }
            else if (ChineseLunisolarDate == "二月初二" || ChineseLunisolarDate == "闰二月初二")
            {
                return "龙抬头";
            }
            else if (ChineseLunisolarDate == "五月初五" || ChineseLunisolarDate == "闰五月初五")
            {
                return "端午节";
            }
            else if (ChineseLunisolarDate == "七月初七" || ChineseLunisolarDate == "闰七月初七")
            {
                return "七夕节";
            }
            else if (ChineseLunisolarDate == "七月十四" || ChineseLunisolarDate == "闰七月十四")
            {
                return "南方中元节";
            }
            else if (ChineseLunisolarDate == "七月十五" || ChineseLunisolarDate == "闰七月十五")
            {
                return "北方中元节";
            }
            else if (ChineseLunisolarDate == "八月十五" || ChineseLunisolarDate == "闰八月十五")
            {
                return "中秋节";
            }
            else if (ChineseLunisolarDate == "九月初九" || ChineseLunisolarDate == "闰九月初九")
            {
                return "重阳节";
            }
            else if (ChineseLunisolarDate == "十月初一" || ChineseLunisolarDate == "闰十月初一")
            {
                return "寒衣节";
            }
            else if (ChineseLunisolarDate == "十月十五" || ChineseLunisolarDate == "闰十月十五")
            {
                return "下元节";
            }
            else if (ChineseLunisolarDate == "腊月初八" || ChineseLunisolarDate == "闰腊月初八")
            {
                return "腊八节";
            }
            else if (ChineseLunisolarDate == "腊月廿三" || ChineseLunisolarDate == "闰腊月廿三")
            {
                return "北方小年";
            }
            else if (ChineseLunisolarDate == "腊月廿四" || ChineseLunisolarDate == "闰腊月廿四")
            {
                return "南方小年";
            }
            #endregion
            #region 公历节日
            else if (DateTime.Now.ToString("MMdd") == "0101")
            {
                return "元旦节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0202")
            {
                return "世界湿地日";
            }
            else if (DateTime.Now.ToString("MMdd") == "0214")
            {
                return "情人节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0308")
            {
                return "妇女节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0312")
            {
                return "植树节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0315")
            {
                return "消费者权益日";
            }
            else if (DateTime.Now.ToString("MMdd") == "0401")
            {
                return "愚人节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0422")
            {
                return "世界地球日";
            }
            else if (DateTime.Now.ToString("MMdd") == "0501")
            {
                return "劳动节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0504")
            {
                return "青年节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0512")
            {
                return "国际护士节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0518")
            {
                return "国际博物馆日";
            }
            else if (DateTime.Now.ToString("MMdd") == "0601")
            {
                return "儿童节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0605")
            {
                return "世界环境日";
            }
            else if (DateTime.Now.ToString("MMdd") == "0623")
            {
                return "奥林匹克日";
            }
            else if (DateTime.Now.ToString("MMdd") == "0701")
            {
                return "建党节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0801")
            {
                return "建军节";
            }
            else if (DateTime.Now.ToString("MMdd") == "0910")
            {
                return "教师节";
            }
            else if (DateTime.Now.ToString("MMdd") == "1001")
            {
                return "国庆节";
            }
            else if (DateTime.Now.ToString("MMdd") == "1124")
            {
                return "平安夜";
            }
            else if (DateTime.Now.ToString("MMdd") == "1125")
            {
                return "圣诞节";
            }
            else if (DateTime.Now.ToString("MMdd") == "1201")
            {
                return "世界艾滋病日";
            }
            else if (DateTime.Now.ToString("MMdd") == "1213")
            {
                return "国家公祭日";
            }
            else if (DateTime.Now.ToString("MMdd") == "1224")
            {
                return "平安夜";
            }
            else if (DateTime.Now.ToString("MMdd") == "1225")
            {
                return "圣诞节";
            }
            #endregion
            #region 非固定节日
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190105" || DateTime.Now.ToString("yyyyMMdd") == "20200106")
            {
                return "小寒";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190120" || DateTime.Now.ToString("yyyyMMdd") == "20200120")
            {
                return "大寒";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190204" || DateTime.Now.ToString("yyyyMMdd") == "20200124")
            {
                return "除夕";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20200204")
            {
                return "立春";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20200219")
            {
                return "雨水";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190306" || DateTime.Now.ToString("yyyyMMdd") == "20200305")
            {
                return "惊蛰";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190321" || DateTime.Now.ToString("yyyyMMdd") == "20200320")
            {
                return "春分";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190405" || DateTime.Now.ToString("yyyyMMdd") == "20200404")
            {
                return "清明节";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190420" || DateTime.Now.ToString("yyyyMMdd") == "20200419")
            {
                return "谷雨";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190506" || DateTime.Now.ToString("yyyyMMdd") == "20200505")
            {
                return "立夏";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190512" || DateTime.Now.ToString("yyyyMMdd") == "20200510")
            {
                return "母亲节";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190521" || DateTime.Now.ToString("yyyyMMdd") == "20200520")
            {
                return "小满";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190606" || DateTime.Now.ToString("yyyyMMdd") == "20200605")
            {
                return "芒种";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190616" || DateTime.Now.ToString("yyyyMMdd") == "20200621")
            {
                return "父亲节";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190621" || DateTime.Now.ToString("yyyyMMdd") == "20200621")
            {
                return "夏至";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190707" || DateTime.Now.ToString("yyyyMMdd") == "20200706")
            {
                return "小暑";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190723" || DateTime.Now.ToString("yyyyMMdd") == "20200722")
            {
                return "大暑";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190808" || DateTime.Now.ToString("yyyyMMdd") == "20200807")
            {
                return "立秋";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190823" || DateTime.Now.ToString("yyyyMMdd") == "20200822")
            {
                return "处暑";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190908" || DateTime.Now.ToString("yyyyMMdd") == "20200907")
            {
                return "白露";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20190923" || DateTime.Now.ToString("yyyyMMdd") == "20200922")
            {
                return "秋分";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20191008" || DateTime.Now.ToString("yyyyMMdd") == "20201008")
            {
                return "寒露";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20191024" || DateTime.Now.ToString("yyyyMMdd") == "20201023")
            {
                return "霜降";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20191108" || DateTime.Now.ToString("yyyyMMdd") == "20201107")
            {
                return "立冬";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20191122" || DateTime.Now.ToString("yyyyMMdd") == "20201122")
            {
                return "小雪";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20191128" || DateTime.Now.ToString("yyyyMMdd") == "20201126")
            {
                return "西方感恩节";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20191207" || DateTime.Now.ToString("yyyyMMdd") == "20201207")
            {
                return "大雪";
            }
            else if (DateTime.Now.ToString("yyyyMMdd") == "20191222" || DateTime.Now.ToString("yyyyMMdd") == "20201221")
            {
                return "冬至";
            }
            #endregion
            #region 无节日
            else
            {
                return "无节日";
            }
            #endregion
        }
        #endregion
    }
    #endregion
}

14、在MyApp项目上右键-添加-类,名称为ImageHelper.cs,添加如下代码:

using System.Drawing;

namespace MyApp
{
    public class ImageHelper
    {
        /// <summary>
        /// 获取均分图片中的某一块
        /// </summary>
        /// <param name="orignal">原始图片</param>
        /// <param name="count">均分数</param>
        /// <param name="index">均分数序号</param>
        /// <returns>均分后指定块图片</returns>
        public static Image GetImagebyAverageIndex(Image orignal, int count, int index)
        {
            int width = orignal.Width / count;
            return CutImage(orignal, width * (index - 1), width, orignal.Height);
        }

        /// <summary>
        /// 获取均分图片
        /// </summary>
        /// <param name="orignal">原始图片</param>
        /// <param name="start">入点</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <returns></returns>
        private static Image CutImage(Image orignal, int start, int width, int height)
        {
            Bitmap partImage = new Bitmap(width, height);
            Graphics graphics = Graphics.FromImage(partImage);
            Rectangle srcRect = new Rectangle(start, 0, width, height);
            Rectangle destRect = new Rectangle(0, 0, width, height);
            graphics.DrawImage(orignal, destRect, srcRect, GraphicsUnit.Pixel);
            partImage.MakeTransparent(Color.FromArgb(255, 0, 255));
            graphics.Dispose();
            return partImage;
        }
    }
}

15、打开FormMain.cs代码编辑器,添加如下代码:

using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace MyApp
{
    public partial class FormMain : Framework.FormMain
    {
        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            //初始化图片按钮控件图片显示
            PictureBoxCloseWindow.Image = ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonClose, 3, 1);
            PictureBoxMaximizeBox.Image = ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonMaximize, 3, 1);
            PictureBoxMinimizeBox.Image = ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonMinimize, 3, 1);
            PictureBoxRestoreWindow.Image = ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonRestore, 3, 1);

            //加载操作系统版本
            LabelOSVersion.Text = OSInformation.GetOSFullVersion();

            //加载系统时间
            ShowNowTime();
        }

        #region 自绘标题栏
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        private void PanelTitle_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
                if (WindowState == FormWindowState.Normal)
                {
                    ReleaseCapture();
                    SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
                }
            }
            else if (e.Button == MouseButtons.Left && e.Clicks == 2)
            {
                if (WindowState == FormWindowState.Normal)
                {
                    FormBorderStyle = FormBorderStyle.None;
                    MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);//不遮盖任务栏
                    WindowState = FormWindowState.Maximized;
                    PictureBoxMaximizeBox.Visible = false;
                    PictureBoxRestoreWindow.Visible = true;
                }
                else if (WindowState == FormWindowState.Maximized)
                {
                    WindowState = FormWindowState.Normal;
                    PictureBoxMaximizeBox.Visible = true;
                    PictureBoxRestoreWindow.Visible = false;
                }
            }
        }
        #endregion

        #region 窗体没有焦点 窗体可拖动
        #region 窗体无焦点
        private void SetChildControlNoFocus(Control ctrl)
        {
            if (ctrl.HasChildren)
                foreach (Control c in ctrl.Controls)
                {
                    SetControlNoFocus(c);
                }
        }

        readonly MethodInfo SetControlStyleMethod = null;
        readonly object[] SetControlStyleArgs = new object[] { ControlStyles.Selectable, false };
        private void SetControlNoFocus(Control ctrl)
        {
            SetControlStyleMethod.Invoke(ctrl, SetControlStyleArgs);
            SetChildControlNoFocus(ctrl);
        }
        #endregion
        #region 无边框拖动窗体
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        #endregion
        #endregion

        #region 位图按钮
        private void FormClickMeans(int tag)
        {
            switch (tag)
            {
                case 0://关闭事件
                    Application.Exit();
                    break;
                case 1://最大化事件
                    MaximumSize = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);//不遮盖任务栏
                    WindowState = FormWindowState.Maximized;
                    PictureBoxMaximizeBox.Visible = false;
                    PictureBoxRestoreWindow.Visible = true;
                    break;
                case 2://最小化事件
                    WindowState = FormWindowState.Minimized;
                    break;
                case 3://还原事件
                    WindowState = FormWindowState.Normal;
                    PictureBoxMaximizeBox.Visible = true;
                    PictureBoxRestoreWindow.Visible = false;
                    break;
            }
        }

        private static PictureBox picture = new PictureBox();
        private void ImageSwitch(object sender, int tag, int i)
        {
            picture = (PictureBox)sender;
            switch (tag)
            {
                case 0://关闭按钮图片
                    picture.Image = null;
                    if (i == 0)//鼠标离开
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonClose, 3, 1);
                    }
                    else if (i == 1)//鼠标进入
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonClose, 3, 2);
                    }
                    else if (i == 2)//鼠标按下
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonClose, 3, 3);
                    }
                    break;
                case 1://关闭按钮图片
                    picture.Image = null;
                    if (i == 0)//鼠标离开
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonMinimize, 3, 1);
                    }
                    else if (i == 1)//鼠标进入
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonMinimize, 3, 2);
                    }
                    else if (i == 2)//鼠标按下
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonMinimize, 3, 3);
                    }
                    break;
                case 2://关闭按钮图片
                    picture.Image = null;
                    if (i == 0)//鼠标离开
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonMaximize, 3, 1);
                    }
                    else if (i == 1)//鼠标进入
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonMaximize, 3, 2);
                    }
                    else if (i == 2)//鼠标按下
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonMaximize, 3, 3);
                    }
                    break;
                case 3://关闭按钮图片
                    picture.Image = null;
                    if (i == 0)//鼠标离开
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonRestore, 3, 1);
                    }
                    else if (i == 1)//鼠标进入
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonRestore, 3, 2);
                    }
                    else if (i == 2)//鼠标按下
                    {
                        picture.Image = Common.ImageHelper.GetImagebyAverageIndex(Properties.Resources.ButtonRestore, 3, 3);
                    }
                    break;
            }
        }

        /// <summary>
        /// 鼠标点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PictureBox_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && e.Clicks == 1)
            {
                FormClickMeans(Convert.ToInt16(((PictureBox)sender).Tag.ToString()));
            }
        }

        private void PictureBox_MouseEnter(object sender, EventArgs e)
        {
            ImageSwitch(sender, Convert.ToInt16(((PictureBox)sender).Tag.ToString()), 1);
        }

        private void PictureBox_MouseLeave(object sender, EventArgs e)
        {
            ImageSwitch(sender, Convert.ToInt16(((PictureBox)sender).Tag.ToString()), 0);
        }

        private void PictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            ImageSwitch(sender, Convert.ToInt16(((PictureBox)sender).Tag.ToString()), 2);
        }

        private void PictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            ImageSwitch(sender, Convert.ToInt16(((PictureBox)sender).Tag.ToString()), 1);
        }
        #endregion

        #region 使用线程显示当前时间
        /// <summary>
        /// 使用线程方式显示当前时间
        /// </summary>
        private void ShowNowTime()
        {
            new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        LabelNowTime.BeginInvoke(new MethodInvoker(() =>
                        LabelNowTime.Text = DateInformation.GetSystemDateTime() + " " + DateInformation.GetDayOfWeek() + " " + DateInformation.GetChineseLunisolarCalendar()
                        ));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    Thread.Sleep(500);
                }
            })
            { IsBackground = true }.Start();
        }
        #endregion
    }
}

16、编译生成。



版权声明:本文为MissPuya原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。