问题描述
WinForms 文本框是否有任何属性可以在框的末尾嵌入按钮?
Do WinForms textboxes have any properties that make an embedded button, at the end of the box, possible?
类似于 Chrome 地址框中的收藏夹按钮:
Something like the favorites button on the Chrome address box:
我还在某些 Excel 表单中看到过类似以下内容:
I've also seen something like the following in some Excel forms:
编辑
我按照 Hans Passant 的回答添加了一个点击事件处理程序,它似乎工作正常:
I've followed Hans Passant's answer with the addition of a click event handler and it seem to work ok:
protected override void OnLoad(EventArgs e) {
var btn = new Button();
btn.Size = new Size(25, textBoxFolder.ClientSize.Height + 2);
btn.Location = new Point(textBoxFolder.ClientSize.Width - btn.Width, -1);
btn.Cursor = Cursors.Default;
btn.Image = Properties.Resources.arrow_diagright;
btn.Click += btn_Click;
textBoxFolder.Controls.Add(btn);
// Send EM_SETMARGINS to prevent text from disappearing underneath the button
SendMessage(textBoxFolder.Handle, 0xd3, (IntPtr)2, (IntPtr)(btn.Width << 16));
base.OnLoad(e);
}
[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");
}
推荐答案
获取 TextBox 内的按钮只需要将其添加到该框的 Controls 集合中.您还需要做一些合理的事情来防止框内的文本在按钮下方消失;这需要一点点pinvoke.像这样:
Getting the button inside the TextBox just requires adding it to the box' Controls collection. You'll also need to do something reasonable to prevent the text inside the box disappearing underneath the button; that requires a wee bit of pinvoke. Like this:
protected override void OnLoad(EventArgs e) {
var btn = new Button();
btn.Size = new Size(25, textBox1.ClientSize.Height + 2);
btn.Location = new Point(textBox1.ClientSize.Width - btn.Width, -1);
btn.Cursor = Cursors.Default;
btn.Image = Properties.Resources.star;
textBox1.Controls.Add(btn);
// Send EM_SETMARGINS to prevent text from disappearing underneath the button
SendMessage(textBox1.Handle, 0xd3, (IntPtr)2, (IntPtr)(btn.Width << 16));
base.OnLoad(e);
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
当我测试右边距时看起来像这样(应该选择更漂亮的位图):
Looked like this while I tested the right margin (should have picked a prettier bitmap):
这篇关于WinForms 文本框中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!