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

发布于 2024-12-03 15:45:38 字数 133 浏览 0 评论 0原文

在我们的应用程序中,我们在白色表单上有白色按钮。当鼠标悬停在按钮上时,我们希望在按钮上显示一个浅蓝色透明矩形。

我想创建这个用户控件,但我不知道该怎么做。我尝试过谷歌,但没有找到任何可以帮助我的东西,所以我希望你们能给我指出正确的方向。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等待我真够勒 2024-12-10 15:45:38

您可以从 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文