[.NET]讓Winform畫面,按下Enter也能像按Tab一樣,切到另一個Textbox

要讓Winform畫面可以按下Enter也能像按Tab一樣,可透過SelectNextControl去設定,但是,如果要限定只能在TextBox中切換要如何做呢?

有朋友在問「TextBox_Leave 事件觸發」的問題

主要就是要讓Winform畫面可以按下Enter也能像按Tab一樣,切換!

image

 

一開始想到做法就是在Form的KeyDown事件中處理,如下,

1.設定TextBox的TabIndex屬性(依您要的順序0~n)

2.設定Form的Keypreview屬性為true

3.在Form的KeyDown Event中將Enter轉成Tab

如下,

C#


private void Form1_KeyDown(object sender, KeyEventArgs e)
{
	if (e.KeyCode == Keys.Enter)
	{
		this.SelectNextControl(this.ActiveControl, true, true, true, true);
	}
}

 

VB.NET


Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
	If e.KeyCode = Keys.Enter Then
		Me.SelectNextControl(Me.ActiveControl, True, True, True, True)
	End If
End Sub

 

但是可收Focus的控制項不只有TextBox,還有Button等其他控制項。

所以就不可以單使用 SelectNextControl 而已,還要加入判斷。

所以就要搭配 GetNextControl 來判斷是否為TextBox,不是的話,就再取下一個,如下,

C#


private void Form1_KeyDown(object sender, KeyEventArgs e)
{
	if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
	{
		Control ctrl = this.GetNextControl(this.ActiveControl, true);
		while (ctrl is TextBox == false) 
		{
			ctrl = this.GetNextControl(ctrl, true);
		}
		ctrl.Focus();
	}
}

 

VB.NET


Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
	If e.KeyCode = Keys.Enter OrElse e.KeyCode = Keys.Tab Then
		Dim ctrl As Control = Me.GetNextControl(Me.ActiveControl, True)
			While (TypeOf (ctrl) Is TextBox = False)
				ctrl = Me.GetNextControl(ctrl, True)
			End While
			ctrl.Focus()
	End If
End Sub

 

但是測試後發現,Tab居然不會進Form的KeyDown事件之中,於是參考「How to intercept capture TAB key in WinForms application?」,覆寫ProcessCmdKey來處理Enter及Tab,如下,

C#


protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
	Keys keyPressed = (Keys)msg.WParam.ToInt32();
	switch (keyPressed)
	{
		case Keys.Enter:
		case Keys.Tab:
			Control ctrl = this.GetNextControl(this.ActiveControl, true);
			while (ctrl is TextBox == false) 
			{
				ctrl = this.GetNextControl(ctrl, true);
			}
			ctrl.Focus();
			return true;
		default:
			return base.ProcessCmdKey(ref msg, keyData);
	}
}

 

VB.NET


Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
	Dim keyPressed As Keys = CType(msg.WParam.ToInt32(), Keys)
	Select Case keyPressed
		Case Keys.Enter, Keys.Tab
			Dim ctrl As Control = Me.GetNextControl(Me.ActiveControl, True)
			While (TypeOf (ctrl) Is TextBox = False)
				ctrl = Me.GetNextControl(ctrl, True)
			End While
			ctrl.Focus()
			Return True
		Case Else
			Return MyBase.ProcessCmdKey(msg, keyData)
	End Select
End Function

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^