c# - 创建一个可以快速更新的无闪烁文本框

标签 c# textbox winforms

我正在尝试创建一个搜索工具,并希望在文本框中显示结果,就像 Visual Studio 中包含的那样——这意味着对于长搜索,结果将附加到文本框的末尾当用户试图查看文本框顶部的结果时。

目前我使用的是标准文本框,但是它有很多问题:

  • 搜索过程中文本框疯狂闪烁
  • 当结果附加到框时,用户无法滚动
  • 用户无法在附加结果时将结果复制并粘贴到文本框中。

有什么方法可以解决这些问题,还是我应该考虑使用其他控件/创建自己的控件?

最佳答案

Microsoft 忘记为 TextBox 实现 Begin/EndUpdate() 方法。您可以自己添加它们,它可以解决问题。但是,您无法摆脱闪烁。示例代码:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            timer1.Interval = 10;
            timer1.Tick += new EventHandler(timer1_Tick);
            button1.Click += new EventHandler(button1_Click);
        }
        void timer1_Tick(object sender, EventArgs e) {
            int pos = textBox1.SelectionStart;
            int len = textBox1.SelectionLength;
            SendMessage(textBox1.Handle, 11, IntPtr.Zero, IntPtr.Zero);
            textBox1.AppendText(DateTime.Now.ToString() + Environment.NewLine);
            SendMessage(textBox1.Handle, 11, (IntPtr)1, IntPtr.Zero);
            //if (textBox1 is RichTextBox) textBox1.Invalidate();
            textBox1.SelectionStart = pos;
            textBox1.SelectionLength = len;
        }
        private void button1_Click(object sender, EventArgs e) {
            timer1.Enabled = !timer1.Enabled;
        }
        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
    }
}

关于c# - 创建一个可以快速更新的无闪烁文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2072622/

相关文章:

jquery - 更改文本框的颜色

vb.net - 文本框中的当前关键位置

c# - 使用 Windows 拖动复制光标

c# - 有多个工具提示/弹出窗口整齐地堆叠在 Windows 系统托盘区域,类似于 Messenger/反病毒通知

c# - Xamarin.Forms - 按钮按下和释放事件

javascript - 动态将从 Controller 返回的选择框值呈现为 json

c# - Controller 和操作的 MVC 属性

c# - 如何在 C# 中使用 XPath 检索最后一个节点?

user-interface - 为什么 MATPLOTLIB 中的文本框这么慢?

c# - 长按按钮