2013-05-11 33 views
0

以下代碼在焦點發生變化時更改文本框的屬性,並在焦點丟失後恢復更改。我在使用Enter,Leave,GotFocus,LostFocus事件時遇到問題,因爲它們在單擊或切換到文本框時以不同的順序出現。以下代碼僅在文本框之間切換但不能單擊時按預期行事。如果我更改txtBoxes_ReminderOffFocus來處理Leave事件而不是LostFocus,那麼它在按文本框之間單擊而不是Tab鍵時按預期工作。文本框焦點 - 點擊與選項卡使用VB

Private Sub txtBoxes_ReminderOnFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtHrsWkd.Enter, txtPayRate.Enter, txtFedTaxRate.Enter, txtStTaxRate.Enter 
    If sender.Text = "(Numeric Value)" Or sender.Text = "(Percentage)" Then 
     Debug.Print("New textbox focused onto.")  'Sets up textboxes for standard input, if they have initial reminder. Check control.enter event for more on focus orderings. 
     sender.Clear() 
     sender.TextAlign = HorizontalAlignment.Left 
     sender.ForeColor = Color.Black 
    End If 
End Sub 

Private Sub txtBoxes_ReminderOffFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtHrsWkd.LostFocus, txtPayRate.LostFocus, txtFedTaxRate.LostFocus, txtStTaxRate.LostFocus 
    If sender.Text = "" Then 
     Debug.Print("A textbox has lost focus.") 
     sender.ForeColor = Color.Gray    'if textbox is empty, fills in initial "numeric value" or "percentage" reminder. 
     sender.TextAlign = HorizontalAlignment.Right 
     If sender Is txtHrsWkd Or sender Is txtPayRate Then 
      sender.Text = "(Numeric Value)" 
     Else 
      sender.Text = "(Percentage)" 
     End If 
    End If 
End Sub 

在 'txtBoxes_ReminderOffFocus'

.LostFocus事件工作文本框之間的互聯,而不是當點擊預期。

。如果在文本框之間進行單擊而不是按Tab鍵,則按預期方式生成的離開事件將按預期工作。

+0

[WinForms中的水印文本框]的可能重複(http://stackoverflow.com/questions/4902565/watermark-textbox-in-winforms) – 2013-05-11 22:21:39

回答

0

由於.LostFocus適用於製表和不點擊,.Leave適用於單擊和非製圖時,您是否可以嘗試設置txtBoxes_ReminderOffFocus來處理這兩個事件?

+0

單擊/選項卡設置.Leave和.LostFocus事件但它們跟隨不同的順序,如下面的'備註'所示:http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx – 2013-05-13 22:23:07

+0

我想它不清楚什麼是不工作。 LostFocus和Leave按不同順序發生,但兩種情況都發生在Enter和GotFocus事件之後,而您沒有處理其他事件。所以我不確定你有什麼不同。 – Kratz 2013-05-14 12:36:33