Button inside a WinForms textbox

前端 未结 7 1114
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 14:31

Do WinForms textboxes have any properties that make an embedded button, at the end of the box, possible?

Something like the favorites button on the Chrome address bo

7条回答
  •  一整个雨季
    2020-11-27 15:09

    I saw in Reflector that Control contains "SendMessage(int,int,int)" method and I found another way.

    using System;
    using System.Reflection;
    using System.Windows.Forms;
    
    static class ControlExtensions
    {
        static BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
        static Type[] SendMessageSig = new Type[] { typeof(int), typeof(int), typeof(int) };
    
        internal static IntPtr SendMessage(this Control control, int msg, int wparam, int lparam)
        {
            MethodInfo MethodInfo = control.GetType().GetMethod("SendMessage", flags, null, SendMessageSig, null);
    
            return (IntPtr)MethodInfo.Invoke(control, new object[] { msg, wparam, lparam });
        }
    }
    

    Now by overriding WndProc in ButtonTextBox we can achieve desired effect.

    public class ButtonTextBox : TextBox
    {
        Button button;
    
        public ButtonTextBox()
        {
            this.button = new Button();
            this.button.Dock = DockStyle.Right;
            this.button.BackColor = SystemColors.Control;
            this.button.Width = 21;
            this.Controls.Add(this.button);
        }
    
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
    
            switch (m.Msg)
            {
                case 0x30:
                    int num = this.button.Width + 3;
                    this.SendMessage(0xd3, 2, num << 16);
                    return;
            }
        }
    }
    

    And I think this is much safer way.

提交回复
热议问题