[VB.NET]動態產生的控制項 設定MouseDown

動態產生的控制項 設定MouseDown

一般從工具箱拉出來的控制項,我們可以透過form的Acceptbutton屬性去設定 按enter 會觸發那個按鈕

但用動態產生的控制項 用me.Acceptbutton=button就不會有反應

所以我們要在textbox 上 繫結 按下keydown的事件,讓他在按下enter時,會去 呼叫按下button 的事件

以下為範例程式碼

Public Class Form1
    Dim point As New Point()
    Dim fnt As Font
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim txtPassword As New TextBox
        txtPassword.Name = "txtPassword"
        txtPassword.PasswordChar = "*"
        point.X = 20
        point.Y = 10
        txtPassword.Text = ""
        txtPassword.Width = 80
        txtPassword.Location = point
        fnt = txtPassword.Font
        AddHandler txtPassword.KeyDown, AddressOf txtPassword_KeyDown
        txtPassword.Font = New Font(fnt.Name, 20, FontStyle.Bold)
        Me.Controls.Add(txtPassword)
        Dim btn_ok As New Button
        btn_ok.Name = "btn_ok"
        btn_ok.Text = "確定"
        btn_ok.BackColor = System.Drawing.Color.FromArgb(155, 155, 155)
        btn_ok.ForeColor = System.Drawing.Color.FromArgb(0, 0, 0)
        point.X = 20
        point.Y = 70
        btn_ok.Location = point
        fnt = btn_ok.Font
        btn_ok.Font = New Font(fnt.Name, 12, FontStyle.Regular)
        btn_ok.Width = 80
        btn_ok.Height = 40
        btn_ok.FlatStyle = FlatStyle.Flat
        AddHandler btn_ok.MouseDown, AddressOf btn_ok_MouseDown
        Me.Controls.Add(btn_ok)
        'Me.AcceptButton = btn_ok
        '動態產生的控制項 用AcceptButton 屬性無效
        Me.Focus()
        txtPassword.Focus()
    End Sub
    Private Sub txtPassword_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        Dim btnsure As New Button
        If e.KeyCode = Keys.Enter Then '按下enter觸發btn_ok_MouseDown事件
            btnsure = CType(Me.Controls.Find("btn_ok", False)(0), Button)
            btn_ok_MouseDown(Me, Nothing)
        End If
    End Sub
    Sub btn_ok_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim txtPassword As New TextBox
        txtPassword = CType(Me.Controls.Find("txtPassword", False)(0), TextBox)
        If txtPassword.Text = "login" Then
            MsgBox("登錄成功")
        Else
            MsgBox("登錄失敗")
        End If
    End Sub
End Class

如有錯誤 歡迎指正