我想在文本框中按下回车键时模拟按钮单击。我之前也使用过这个,但它现在似乎没有用。
请检查我在下面使用的代码,如果我错过了什么,请告诉我。我已经离开编码差不多一年了,也许我错过了什么?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
String uname, password, query;
int counter = 0;
public Form1()
{
InitializeComponent();
}
private void login_Click(object sender, EventArgs e)
{
verify();
}
private void pass_KeyDown(Object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
verify();
}
}
private void verify()
{
uname = name.Text; //Initialize variables
password = pass.Text;
uname = uname.Trim(); //Sanitize input
password = password.Trim();
query = "SELECT * FROM login WHERE uname = @uname AND pass = @pass";
string conString = Properties.Settings.Default.libConnectionString;
using (SqlCeConnection conn = new SqlCeConnection(conString))
{
conn.Open();
using (SqlCeCommand cmd = new SqlCeCommand(query, conn))
{
cmd.Parameters.AddWithValue("@uname", uname);
cmd.Parameters.AddWithValue("@pass", password);
cmd.ExecuteNonQuery();
SqlCeDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
counter = 1;
Variables.username = reader["uname"].ToString();
Variables.passw = reader["pass"].ToString();
if (reader["regid"].ToString() != null)
{
Variables.regid = reader["regid"].ToString();
}
MessageBox.Show(Variables.username + ", you are now logged in!");
}
if (counter == 0)
{
MessageBox.Show("Invalid details");
}
}
}
}
}
}
我在IDE Visual Studio 2012中用C#编码
答案 0 :(得分:1)
每当您创建一个有意处理事件的方法时,您需要确保将该方法注册为所需事件的处理程序。如果您没有这样做,程序将不会猜测您的方法是一个事件处理程序。
答案 1 :(得分:-1)
试试这个:
if (args.KeyCode == Keys.Return)
{
login_Click.PerformClick();
}