简体   繁体   English

C#Winforms如何在鼠标悬停在按钮上绘制矩形?

[英]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. 我已经尝试过Google,但是我没有找到任何可以帮助我的东西,因此希望你们能为我指明正确的方向。

You can just derive your own WinForms control from a Button and override the OnPaint event. 您可以仅从Button派生您自己的WinForms控件,并覆盖OnPaint事件。 In the event handler you'll have an PaintEventArg parameter that contains the property called Graphics . 在事件处理程序中,您将具有一个PaintEventArg参数,该参数包含名为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 这是直接来自MSDN的示例: http : //msdn.microsoft.com/zh-cn/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 . 基本上,您必须重写两个事件并添加一个属性,该属性显示控件是否应该使用覆盖矩形绘制,例如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() . 触发OnMouseEnter事件后,立即检查是否设置了IsDrawRectangle,如果未设置,则将其设置为true并调用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. Invalidate()方法将强制重新绘制控件,然后在OnPaint事件中再次检查IsDrawRectangle属性的值,并在需要时绘制矩形。 You also have to override OnMouseLeave to set the property back to false and force the repaint to remove the rectangle. 您还必须重写OnMouseLeave以将属性设置为false,并强制重新绘制以删除矩形。

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. 补充:如果您需要重绘的不仅仅是一个控件(以防您的矩形覆盖了其他需要重绘的控件),则将要重绘的所有内容都放在一个容器中,并调用Parent.Invalidate()事件处理程序中的Parent.Invalidate()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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