C# Winforms 如何在鼠标悬停的按钮上绘制矩形?
在我们的应用程序中,我们在白色表单上有白色按钮。当鼠标悬停在按钮上时,我们希望在按钮上显示一个浅蓝色透明矩形。
我想创建这个用户控件,但我不知道该怎么做。我尝试过谷歌,但没有找到任何可以帮助我的东西,所以我希望你们能给我指出正确的方向。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以从
Button
派生您自己的 WinForms 控件并重写OnPaint
事件。在事件处理程序中,您将有一个PaintEventArg
参数,其中包含名为Graphics
的属性。您可以使用此属性直接在控件所在的位置绘制任何您想要的内容。以下是直接来自 MSDN 的示例: http:// /msdn.microsoft.com/en-us/library/system.windows.forms.control.onpaint.aspx
添加:刚刚重新阅读您的问题,发现我没有正确回答。
基本上,您必须重写两个事件并添加一个属性来显示您的控件是否应该使用覆盖的矩形进行绘制,比方说
IsDrawRectangle
。一旦触发OnMouseEnter
事件,您就会检查 IsDrawRectangle 是否已设置,如果没有,请将其设置为 true 并调用this.Invalidate()
。Invalidate()
方法将强制重新绘制控件,然后在OnPaint
事件中,您只需再次检查IsDrawRectangle
的值属性并根据需要绘制矩形。您还必须重写 OnMouseLeave 来将该属性设置回 false 并强制重新绘制以删除矩形。
添加:如果您需要重新绘制的不仅仅是一个控件(如果您的矩形覆盖了一些需要重新绘制的其他控件),则放置您想要重新绘制的所有内容在一个容器中,然后在事件处理程序中调用
Parent.Invalidate()
方法。You can just derive your own WinForms control from a
Button
and override theOnPaint
event. In the event handler you'll have anPaintEventArg
parameter that contains the property calledGraphics
. 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 theOnMouseEnter
event is triggered you check if IsDrawRectangle is set and if not you set it to true and invokethis.Invalidate()
. TheInvalidate()
method will force the control to be re-drawn and then in yourOnPaint
event you just again check the value of yourIsDrawRectangle
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.