c# - WinForms 文本框内的按钮

标签 c# .net winforms

WinForms 文本框是否具有使嵌入按钮成为可能的任何属性,在框的末尾?

类似于 Chrome 地址框中的收藏夹按钮:

enter image description here

我在一些 Excel 表格中也看到类似下面的内容:

enter image description here


编辑

我按照 Hans Passant 的回答添加了一个点击事件处理程序,它似乎工作正常:

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。像这样:

    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);

我测试右边距时看起来像这样(应该选择更漂亮的位图):

enter image description here

关于c# - WinForms 文本框内的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868817/

相关文章:

WPF WindowsFormsHost 不会冒泡未经处理的按键手势

c# - ElasticSearch 查询检索书籍的所有标签

c# - 将多个对象值从 Arraylist 写入控制台

c# - Microsoft.office.interop.word.dll 可以在不安装 office 的情况下运行吗?

c# - 如何使用 C# 将 Windows 系统时钟设置为正确的本地时间?

jquery - Http 处理程序是合适的架构选择吗?

c# - IsAssignableFrom 和 GetInterface 之间有什么区别?

asp.net - 如何从 Windows 应用程序编程(使用 C#.NET 的 WinForms)迁移到 Web 应用程序编程(ASP.NET)?

c++ - 是否可以从非托管 C++ 访问 Winforms?

c# - 根据ComboBox确定MessageBoxIcon