我如何在richTextBox1上拉绳?

时间:2014-06-25 16:57:43

标签: c# .net winforms

我在设计器中创建了一个新的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设计师,但它是空的。我没有看到"你好"。

这个词

1 个答案:

答案 0 :(得分:0)

一种方法是扩展RichTextBox控件并使用OnPaint方法实现自定义绘图。但通常RichTextBox控件不会调用OnPaint方法,因此您必须在WndProc方法中通过hooking手动调用该方法。

示例:

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