Transparent TextBox - OnPaint not firing when changin text

纵然是瞬间 提交于 2019-12-12 05:47:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!