问题
My control properly starts as transparent, but once I enter text, it's going to a regular white background. If I move my mouse over the control, it fires the OnPaint again, and is able to draw the control with text correctly. How can I get it to paint the transparent background when text is being entered?
Default:
Directly after entering text:
After moving mouse over, to force OnPaint to fire:
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);
}
};
回答1:
FYI - Found the solution:
1) Tie the TextChanged event to a method that will fire every time text is entered.
2) In the new method, mark the control: control->Invalidate()
to trigger the re-painting.
来源:https://stackoverflow.com/questions/43739195/transparent-textbox-onpaint-not-firing-when-changin-text