Button停留在MouseDown

时间:2015-06-26 02:55:57

标签: vb.net gdi+ gdi

好吧,我回到了GDI,我遇到了我的第一次尝试,这是在c#中。我将它转换为VB.NET,并没有看到任何错误。但是,当我测试它时,按钮将保持MouseDown状态的颜色,直到我关闭它打开的MessageBox。有什么想法吗?

GDI -

Public Class BasicButton
Inherits Control
Public Enum MouseState
    Normal
    Down
End Enum
Private _mouseState As MouseState = MouseState.Normal
Protected Overrides Sub CreateHandle()
    MyBase.CreateHandle()

End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    Dim g = e.Graphics
    Select Case _mouseState
        Case MouseState.Normal
            g.FillRectangle(Brushes.Orange, ClientRectangle)
            Exit Select
        Case MouseState.Down
            g.FillRectangle(Brushes.DarkOrange, ClientRectangle)
            Exit Select

    End Select
    MyBase.OnPaint(e)
    Dim sf As New StringFormat()
    sf.LineAlignment = StringAlignment.Center
    sf.Alignment = StringAlignment.Center
    g.DrawString(Text, Font, New SolidBrush(Color.White), New Rectangle(0, 0, Width, Height), sf)
End Sub
Private Sub SwitchMouseState(state As MouseState)
    _mouseState = state
    Invalidate()
End Sub
Protected Overrides Sub OnMouseUp(e As MouseEventArgs)
    SwitchMouseState(MouseState.Normal)
    MyBase.OnMouseUp(e)
End Sub
Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
    SwitchMouseState(MouseState.Down)
    MyBase.OnMouseDown(e)
End Sub

End Class

按钮 -

Private Sub BasicButton1_Click(sender As Object, e As EventArgs) Handles BasicButton1.Click
    MessageBox.Show("Text")
End Sub

2 个答案:

答案 0 :(得分:1)

MessageBox.Show是一种在OnMouseDown和OnMouseUp之间调用的阻塞方法。基本上,直到MessageBox.Show方法返回之后才会调用OnMouseUp代码。

答案 1 :(得分:0)

虽然不是答案,但我相信您必须意识到在Paint方法中创建资源应该尽可能少地完成 - 希望根本不可能。在某些情况下,Paint每秒会被调用很多次。

因此,例如您的代码所在的位置:

Dim sf As New StringFormat()
    sf.LineAlignment = StringAlignment.Center
    sf.Alignment = StringAlignment.Center
    g.DrawString(Text, Font, New SolidBrush(Color.White), New Rectangle(0, 0, Width, Height), sf)

您正在创建StringFormatSolidBrushRectangle

可以缓存StringFormat和SolidBrush(通过使它们成为类级变量)。也可以通过使Rectangle成为类级变量并在Resize事件期间更新它来缓存Rectangle。