如何在c#winform应用程序中从标题栏上检测标题栏上的鼠标或鼠标

时间:2013-03-08 12:25:46

标签: c#

我想在标题栏上检测鼠标,或者在我的c#winform应用程序中检测标题栏上的鼠标。 我有一个有效的代码,但问题是当我将鼠标放在win格式的任何区域时,鼠标离开发生,当我把鼠标放在标题栏然后正确的事件调用。这是代码

using System.Runtime.InteropServices;
public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0xA0) // WM_NCMOUSEMOVE
            {
                TrackNcMouseLeave(this);
                //ShowClientArea();
                label1.Text = "mouse move on title bar";
            }
            else if (m.Msg == 0x2A2) // WM_NCMOUSELEAVE
            {
                //HideClientAreaIfPointerIsOut();
                label1.Text = "mouse leave from title bar";
            }

            base.WndProc(ref m);
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            //HideClientAreaIfPointerIsOut();
        }

        private int previouseHeight;

        private void ShowClientArea()
        {
            if (this.ClientSize.Height == 0)
                this.ClientSize = new Size(this.ClientSize.Width, previouseHeight);
        }

        private void HideClientAreaIfPointerIsOut()
        {
            if (this.Bounds.Contains(Cursor.Position))
                return;
            previouseHeight = this.ClientSize.Height;
            this.ClientSize = new Size(this.ClientSize.Width, 0);
        }

        public static void TrackNcMouseLeave(Control control)
        {
            TRACKMOUSEEVENT tme = new TRACKMOUSEEVENT();
            tme.cbSize = (uint)Marshal.SizeOf(tme);
            tme.dwFlags = 2 | 0x10; // TME_LEAVE | TME_NONCLIENT
            tme.hwndTrack = control.Handle;
            TrackMouseEvent(tme);
        }

        [DllImport("user32")]
        public static extern bool TrackMouseEvent([In, Out] TRACKMOUSEEVENT lpEventTrack);

        [StructLayout(LayoutKind.Sequential)]
        public class TRACKMOUSEEVENT
        {
            public uint cbSize;
            public uint dwFlags;
            public IntPtr hwndTrack;
            public uint dwHoverTime;
        }
    }

所以有人请指导我需要改变的结果,当我将鼠标放在身体上然后我不应该得到通知。感谢

0 个答案:

没有答案