如何获得另一个控件的控制图像?

时间:2012-03-19 11:11:31

标签: c#

看这堂课:

public class ControlContainer : Control
{
    public ControlContainer() { DoubleBuffered = true; SetStyle(ControlStyles.SupportsTransparentBackColor, true); }
    Control _Control;
    public Control Control { get { return _Control; } set { _Control = value; SetHandlers(); } }

    public void SetHandlers()
    {
        if (_Control == null) return;
        Region = _Control.Region;
        Size = _Control.Size;
        _Control.Invalidated += new InvalidateEventHandler(_Control_Invalidated);


    }

    void _Control_Invalidated(object sender, InvalidateEventArgs e)
    {

        Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (_Control == null) return;
        Bitmap p = new Bitmap(_Control.Width, _Control.Height);


        _Control.DrawToBitmap(p, new Rectangle(0, 0, _Control.Width, _Control.Height));
        e.Graphics.DrawImage((Image)p, 0, 0);
        base.OnPaint(e);
    }


}

正如您所看到的,此控件的任务是获取另一个控件的图像并绘制它。 但是如果我们处理名为'textBox1'的TextBox控件如下:

假设我们在上面添加了一个类型为ControlContainer的新实例,其名称为controlContainer1,我们将controlContainer1属性'Control'的值赋给textBox1。

为什么我在textBox1中写一些东西'Invalidated'这个事件不会触发?为什么写作指针“|” “DrawToBitmap”方法没有出现?

1 个答案:

答案 0 :(得分:1)

简答:因为TextBox控件不支持事件Invalidated。如果你在文本框的事件TextChanged上调用Invalidate(),它可能会有所帮助。

Longs回答:这是因为Windows内部处理Win32原生文本框的方式。如果您开始编辑,控件没有边框,将创建与文本框相同位置的相同颜色。现在所有事件都转到此Win32内部编辑框。如果您覆盖文本框的OnPaint并使用FillRectangle填充整个文本框,则可以观察到此行为。编辑文本框后,您会立即看到新的编辑框,其格式为“BackColor”的原始颜色。

相关问题