我的控件正确地开始时是透明的,但是一旦我输入文本,它就会变成常规的白色背景。如果我将鼠标移到控件上,它会再次触发OnPaint,并且能够正确地绘制带有文本的控件。如何让它在输入文本时绘制透明背景?
默认值:

紧跟在输入文本之后:

将鼠标移到上方后,要强制OnPaint触发:

ref class CustomTextBox : System::Windows::Forms::TextBox
{
public:
CustomTextBox()
{
SetStyle(ControlStyles::SupportsTransparentBackColor, true);
SetStyle(ControlStyles::OptimizedDoubleBuffer, true); //Tried this both ways
SetStyle(ControlStyles::AllPaintingInWmPaint, true);
SetStyle(ControlStyles::ResizeRedraw, true);
SetStyle(ControlStyles::UserPaint, true);
BackColor = Color::Transparent;
ForeColor = Color::Red;
}
virtual void OnPrint(PaintEventArgs^ e) override
{
System::Windows::Forms::TextBox::OnPrint(e);
Debug::WriteLine("OnPrint: " + this->Text);
}
virtual void OnPaintBackground(PaintEventArgs^ e) override
{
System::Windows::Forms::TextBox::OnPaintBackground(e);
Debug::WriteLine("OnPaintBackground: " + this->Text);
}
virtual void OnPaint(PaintEventArgs^ e) override
{
//System::Windows::Forms::TextBox::OnPaint(e);
//Paint Background
Graphics^ g = e->Graphics;
RectangleF^ bounds = gcnew RectangleF(0, 0, Convert::ToSingle(this->Width - 1), Convert::ToSingle(this->Height - 1));
e->Graphics->FillRectangle(gcnew SolidBrush(this->BackColor), *bounds);
//Paint text
g->DrawString(this->Text,this->Font,gcnew SolidBrush(Color::Red),1,1);
Debug::WriteLine("OnPaint: " + this->Text);
}
};发布于 2017-05-02 22:19:41
仅供参考-找到解决方案:
1)将TextChanged事件绑定到每次输入文本时都会触发的方法。2)在新方法中,标记控件:control->Invalidate()以触发重新绘制。
https://stackoverflow.com/questions/43739195
复制相似问题