所有者绘制文本框以在 WinForms 中使用

Kay*_*Zed 4 .net windows controls textbox winforms

I need a lean & mean TextBox solution. A RichTextBox proves too slow, so I want to go the way of owner drawing, or custom control building.

My need is for a textbox that can handle large text content and offers simple highlighting by drawing colored backgrounds around words or single characters. Important is, that the text string itself does NOT contain markup for this, but rather, the indices of words to mark are stored separately. Indices relative to the start of the text string (also known as the Text property when talking about a .NET TextBox).

I think it will have to involve drawing the text under my own control as the Windows Edit Control will not be able to do what I need.

My application is Windows Forms. What is the proper way to make a control like this, and are there any examples?

And can one make a fast control under .NET? (already assuming native API calls will be needed). Or is this better done in C++?


Addition 1: I think the way to do this is as described by the answer from user MarkIsMobile in the SO question Drawing over a TextBox in .NET Compact Framework. See, the OnPaint of the TextBox is not really useful, as the TextBox is a rather quirky control. The approach as outlined in the answer from MarkIsMobile is as follows:

  • Replace the default Windows Procedure with your own C# delegate
  • But still keep the 'default' behavior, and call 'OldWindowsProc'
  • Do your own custom drawing after this

I haven't been trying this myself yet, but would be interested to see more examples of this.

Also. My current approach is (the same?) to get access to the control via the NativeWindow class and override WndProc. I simply draw over the text with a degree of transparency to create the 'color marker' effect that I'm after, and this works fine actually - but is not perfect. (Are there ways to draw with bitmap blending, only colorizing the background and not the text in the foreground?)

Han*_*ant 5

您无法实际实现自己的 TextBox,编写自己的文本编辑器是一种惩罚。使用现成的东西,比如 ScintillaNET。

编写自己的可滚动标签在某种程度上是可行的。从双缓冲面板开始,使用 OnPaint 绘制文本。如果您不实现自动换行,它只会是一个改进,这使得找出从哪里开始绘制的成本非常高,因为您必须在滚动的第一条可见行之前换行所有文本。计算 AutoScrollMinSize 很昂贵,因为您必须扫描整个文本以计算换行符,确保您不必过于频繁地更新文本。

一般来说,您很可能只会找出为什么 TextBox 如此缓慢。您可以通过将文本量限制为人类可以合理预期阅读的内容来保持其性能。不多。我通过跟踪每个附加文本的长度并在它超过 65536 个字符时将其扔掉一半来做到这一点。一个不错的整数。