Button inside a WinForms textbox

前端 未结 7 1113
没有蜡笔的小新
没有蜡笔的小新 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:06

    Just a small expansion on the accepted solution, to get the button to look and act properly a few tweaks are needed. Here are tweaks for a search box:

        private static readonly int SEARCH_BUTTON_WIDTH = 25;
    
        private void ConfigureSearchBox()
        {
            var btn = new Button();
            btn.Size = new Size(SEARCH_BUTTON_WIDTH, searchBox.ClientSize.Height + 2);
            btn.Dock = DockStyle.Right;
            btn.Cursor = Cursors.Default;
            btn.Image = Properties.Resources.Find_5650;
            btn.FlatStyle = FlatStyle.Flat;
            btn.ForeColor = Color.White;
            btn.FlatAppearance.BorderSize = 0;
            btn.Click += btn_Click;
            searchBox.Controls.Add(btn);
            this.AcceptButton = btn;
            // Send EM_SETMARGINS to prevent text from disappearing underneath the button
            SendMessage(searchBox.Handle, 0xd3, (IntPtr)2, (IntPtr)(btn.Width << 16));
        }
    
        [System.Runtime.InteropServices.DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
    
        private void btn_Click(object sender, EventArgs e)
        {
            MessageBox.Show("hello world");
        }
    

提交回复
热议问题