简体   繁体   中英

C# Winforms How to draw a rectangle on a button on a mouse over?

In our application we have white buttons on a white form. When the mouse hovers the button we want to show a light-blue transparant rectangle over the button.

I want to create this user control, but I don't know how to do this. I've tried google, but I didn;t found anything that could help me, so I hope you guys can point me at the right direction.

You can just derive your own WinForms control from a Button and override the OnPaint event. In the event handler you'll have an PaintEventArg parameter that contains the property called Graphics . You can use this property to draw anything you want directly where you control is located.

Here is an example directly from MSDN: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onpaint.aspx

Added: just re-read your question and found that I didn't not reply it correctly.

Basically, you have to override two events and add one property showing whether your control should be painted with an overlayed rectangle or not, let's say IsDrawRectangle . As soon as the OnMouseEnter event is triggered you check if IsDrawRectangle is set and if not you set it to true and invoke this.Invalidate() . The Invalidate() method will force the control to be re-drawn and then in your OnPaint event you just again check the value of your IsDrawRectangle property and draw the rectangle if needed. You also have to override OnMouseLeave to set the property back to false and force the repaint to remove the rectangle.

Added: if you need to re-draw more than just a single control (in case if your rectangle covers some other controls that need to be re-drawn) then put everything you want to be re-drawn in one container and call the Parent.Invalidate() method in your event handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM