2015-06-26 97 views
0

那麼,我回到GDI中,我遇到了我第一次嘗試,這是在C#中。我將它轉換爲VB.NET,並沒有看到任何錯誤。但是,當我測試它時,按鈕將保持MouseDown狀態的顏色,直到我關閉它打開的MessageBox。有任何想法嗎?按鈕保持在MouseDown中

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 

回答

1

MessageBox.Show是被調用onmousedown事件和OnMouseUp之間的阻擋方法。基本上,只有在MessageBox.Show方法返回之後,纔會調用OnMouseUp代碼。

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。

+0

這是很早以前製作的,我從未使用過GDI,所以非常感謝小費。 –