我如何在richTextBox1上绘制字符串
本文关键字:绘制 字符串 richTextBox1 | 更新日期: 2023-09-27 18:10:12
我在设计器中创建了一个新的UserControl
,我添加了一个richTextBox。然后我在UserControl
构造函数中做了:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ScrollLabelTest
{
public partial class ScrollText : UserControl
{
Font drawFonts1 = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);
Point pt = new Point(50, 50);
public ScrollText()
{
InitializeComponent();
System.Drawing.Font f = new System.Drawing.Font("hi",5);
Graphics e = richTextBox1.CreateGraphics();
e.DrawString("hello",drawFonts1,new SolidBrush(Color.Red),pt);
this.Invalidate();
}
}
}
然后我把新的UserControl
拖到form1
设计器中,但它是空的。
一种方法是扩展RichTextBox
控件并在OnPaint
方法中实现您的自定义绘图。但是通常RichTextBox
控件不会调用OnPaint
方法,所以你必须通过钩接WndProc
方法来手动调用该方法。
的例子:
class ExtendedRTB : System.Windows.Forms.RichTextBox
{
// this piece of code was taken from pgfearo's answer
// ------------------------------------------
// https://stackoverflow.com/questions/5041348/richtextbox-and-userpaint
private const int WM_PAINT = 15;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_PAINT)
{
// raise the paint event
using (Graphics graphic = base.CreateGraphics())
OnPaint(new PaintEventArgs(graphic,
base.ClientRectangle));
}
}
// --------------------------------------------------------
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawString("hello", this.Font, Brushes.Black, 0, 0);
}
}