我有一个可以自定义文本的显示器,当用户自定义它时,我希望显示文本。可用的自定义之一是“x-out”,它应该在文本的所有 5 个字符上绘制一个大“X”。因此,当选中“X-Out”复选框时,它应该从此更新文本:
对此:
该框本身是一个包含在面板中的 RichTextBox。我尝试在面板中使用 Paint 事件,但它会将其绘制在 RichTextBox 下方(即角上的小红线)。我还尝试过使用自定义 RichTextBox 控件,例如 在此网站。这段代码确实有效,但前提是我没有在 RichTextBox 中设置文本和颜色。如果我设置文本和颜色,然后选中复选框,则不会调用 WndProc 方法。如何使用 Message.msg 15 触发 WndProc 方法?这是代码:
表格
public partial class ButtonDataForm : Form
{
CustomRichTextBox button1;
public ButtonDataForm()
{
InitializeComponent()
}
void OnFormLoad(object sender, EventArgs e)
{
cstmRichTextBox = new CustomRichTextBox(richTextBox1);
}
void OnXOutChecked()
{
cstmRichTextBox.IsChecked = xoutCheckbox.Checked;
cstmRichTextBox.ParentTex.Refresh(); // This does not trigger the WndProc message on cstmRichTextBox
}
}
自定义RichTextBox
public class CustomRichTextBox : NativeWindow
{
public RichTextBox ParentTextBox { get; private set; }
Graphics textBoxGraphics;
public bool IsChecked { get; set; }
public CustomRichTextBox(RichTextBox tb)
{
ParentTextBox = tb;
textBoxGraphics = Graphics.FromHwnd(tb.Handle);
AssignHandle(ParentTextBox.Handle);
}
protected override void WndProc(ref Message m}
{
switch(m.Msg)
{
case 15:
parentTextBox.Invalidate();
base.WndProc(ref m);
DrawXOut();
break;
default:
base.WndProc(ref m);
break;
}
}
void DrawXOut()
{
if (IsChecked)
{
Pen xpen = new Pen(ParentTextBox.ForeColor, 3);
Point topLeft = ParentTextBox.Location;
int x1 = topLeft.X + ParentTextBox.Width;
int y1 = topLeft.Y + ParentTextBox.Height;
Point topRight = new Point(x1, topLeft.Y);
Point bottomLeft = new Point(topLeft.X, y1);
Point bottomRight = new Point(x1, y1);
textBoxGraphics.DrawLine(xpen, topLeft, bottomRight);
textBoxGraphics.DrawLine(xpen, bottomLeft, topRight);
}
}
}
这是一种非常不可靠的方法,在控件之上进行绘制并期望它能够在所有可能的场景中工作(并且可能有很多!)。
您可以在文本框顶部放置一个透明图片框,并使用带有两条交叉红线的透明位图。