Handling windows notifications in derived C# user control

前端 未结 3 422
梦谈多话
梦谈多话 2021-01-27 04:07

How can I handle any of the tree view notifications listed here in a C# class that is derived from the .NET TreeView control?

I tried to handle the click notification, f

3条回答
  •  一向
    一向 (楼主)
    2021-01-27 04:58

    It is not that simple. Check the MSDN article, the NM_CLICK notification is delivered as a WM_NOTIFY message. And it is sent to the parent of the treeview. Winforms has plumbing in place to echo it back to the original control to allow the message to be handled by a class derived from TreeView and customize the event handling. That's done by adding 0x2000 to the message, the value of WM_REFLECT in the Winforms source code.

    So the code should look like this:

    using System;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    class ExtendedTreeView : TreeView {
        protected override void WndProc(ref Message m) {
            if (m.Msg == WM_REFLECT + WM_NOFITY) {
                var notify = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR));
                if (notify.code == NM_CLICK) {
                    MessageBox.Show("yada");
                    m.Result = (IntPtr)1;
                    return;
                }
    
            }
            base.WndProc(ref m);
        }
        private const int NM_FIRST = 0;
        private const int NM_CLICK = NM_FIRST - 2;
        private const int WM_REFLECT = 0x2000;
        private const int WM_NOFITY = 0x004e;
    
        [StructLayout(LayoutKind.Sequential)]
        private struct NMHDR {
            public IntPtr hwndFrom;
            public IntPtr idFrom;
            public int code;
        }
    }
    

    Beware that TreeView already does all this, that's how the NodeMouseClick, Click and MouseClick events get generated. The code that does this also works around some quirks in the native control so be sure you really need this before committing to use it. Review the Reference Source if you want to know what's going on.

提交回复
热议问题