C# 当焦点在文本框的自动完成框上时禁用按键事件
在我的项目中,有一个表单C# 当焦点在文本框的自动完成框上时禁用按键事件,c#,winforms,c#-4.0,textbox,key-events,C#,Winforms,C# 4.0,Textbox,Key Events,在我的项目中,有一个表单mainForm,其中有两个文本框txtsername和txtPassword,还有一个按钮btnLogin 我已经给出了以下txtUserName属性: txtUserName属性 AutoCompleteCustomSource - Collection --> Administrator --> Clerk AutoCompleteMode
mainForm
,其中有两个文本框txtsername
和txtPassword
,还有一个按钮btnLogin
我已经给出了以下txtUserName
属性:
txtUserName属性
AutoCompleteCustomSource - Collection
--> Administrator
--> Clerk
AutoCompleteMode - Suggest
AutoCompleteSource - CustomSource
btnLogin\u点击事件
if (txtUserName.Text.Equals("Administrator") && txtPassword.Text.Equals("123"))
{
//function to access admin features
}
else if (txtUserName.Text.Equals("Clerk") && txtPassword.Text.Equals("123"))
{
//function to access clerk features
}
else
{
MessageBox.Show("Please Enter correct details", "Login Error");
}
if (e.KeyCode.Equals(Keys.Enter)) //Invokes whenever Enter is pressed
{
btnLogin_Click(sender,e); //login
}
我已将mainForm
keypreview
设置为true
,并实现了mainForm
的按键事件功能,如下代码所示:
mainForm\u KeyDownEvent
if (txtUserName.Text.Equals("Administrator") && txtPassword.Text.Equals("123"))
{
//function to access admin features
}
else if (txtUserName.Text.Equals("Clerk") && txtPassword.Text.Equals("123"))
{
//function to access clerk features
}
else
{
MessageBox.Show("Please Enter correct details", "Login Error");
}
if (e.KeyCode.Equals(Keys.Enter)) //Invokes whenever Enter is pressed
{
btnLogin_Click(sender,e); //login
}
现在我的问题是,每当焦点放在txtUserName
上并按A
,就会显示下拉列表以选择“Administrator”(在集合中定义,如上面属性中所示)。当我点击键盘上的Enter
时,它显示的是MessageBox,而不是选择“Administrator”。我知道它正在调用mainForm
的keydown事件。如何在文本框下拉框上禁用按键事件,以便我可以按enter
编辑:
我在
公共表单()
中尝试了以下代码:(不工作)
您需要重写keydown事件处理程序
protected override void OnKeyDown(KeyEventArgs e)
{
//call original event handler. Remove it if you don't need it at all.
base.OnKeyDown(e);
//Insert your code here....
}
事实上,你有两个问题 首先,将txtUserName的AutoCompleteMode属性设置为“SuggestAppend”,而不是简单的“SuggestAppend”。这样,如果用户键入第一个或两个字母,正确的条目将自动附加到txtUserName.Text 接下来,按如下方式修改表单代码:
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode.Equals(Keys.Enter)) //Invokes whenever Enter is pressed
{
if (txtPassword.ContainsFocus)
{
btnLogin_Click(sender, e); //login
}
else
{
this.txtPassword.Focus();
}
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text.Equals("Administrator") && txtPassword.Text.Equals("123"))
{
MessageBox.Show("Administrator");
}
else if (txtUserName.Text.Equals("Clerk") && txtPassword.Text.Equals("123"))
{
MessageBox.Show("Clerk");
}
else
{
MessageBox.Show("Please Enter correct details", "Login Error");
}
}
在上面的例子中,Key-Down事件处理代码测试密码文本框是否有焦点(这意味着用户可能已经输入了用户名和密码,并且准备提交数据)。如果是,则调用btnLogin_Click事件。否则,(意味着txtUserName可能具有焦点)控件将传递给txtPassword以继续数据输入
更新:回复您的评论:
只需按如下方式终止键关闭事件处理程序中的逻辑:
修订事件处理守则:
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode.Equals(Keys.Enter)) //Invokes whenever Enter is pressed
{
btnLogin_Click(sender, e); //login
}
}
注意,另一个小改进(考虑到代码的整体结构)是使用组合框选择用户名,并将自动完成源设置为“ListItems”,然后输入与文本框相同的选项。这需要用户从预定义列表中进行选择。这仍然存在与前面类似的可伸缩性问题,但是如果用户在输入用户名数据时只是输入错误,则无需执行不必要的步骤
请记住,用户往往不喜欢弹出消息造成不必要的中断。允许他们从下拉列表中选择适当的“用户名”,键入适当的密码,然后继续
有一些更好的方法来完成这一切,但这应该调整你的工作秩序
最后,请允许我指出,最终您可能希望找到一种更可靠的方法来执行此类验证。当您需要添加用户时(在您的代码中,这些用户更多地被定义为“组”),您将需要添加到条件事件处理树中
您可以检查在加密文件或数据库中持久化用户名和密码,并在运行时将其加载到字典或其他内容中。然后对用户/密码执行密钥/值查找
或者别的什么
不管怎样,希望这有帮助
更新2:一次完成所有代码。这应该按照您要求的方式进行:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.KeyDown +=new KeyEventHandler(Form1_KeyDown);
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode.Equals(Keys.Enter)) //Invokes whenever Enter is pressed
{
btnLogin_Click(sender, e); //login
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text.Equals("Administrator") && txtPassword.Text.Equals("123"))
{
MessageBox.Show("Administrator");
}
else if (txtUserName.Text.Equals("Clerk") && txtPassword.Text.Equals("123"))
{
MessageBox.Show("Clerk");
}
else
{
MessageBox.Show("Please Enter correct details", "Login Error");
}
}
}
}
您根本不应该处理Enter键。您可以删除
KeyDown
处理程序,而是使用来设置按下Enter键时“单击”的按钮。如果其他控件已经处理了Enter键,则此操作不应该“单击”按钮
对于您的情况来说,这还不够,因为Windows的标准行为是按Enter键来按默认按钮。例如,按Win+R以获得Run…对话框,开始键入C:\Use,按Down选择C:\Users,按Enter,然后查看发生了什么
为了覆盖该行为,您需要让文本框告诉表单它将处理Enter键本身,以便表单不会将其发送到默认按钮。这可以通过创建派生类并覆盖IsInputKey
:
public class MyTextBox : TextBox
{
protected override bool IsInputKey(Keys keyData)
{
return base.IsInputKey(keyData) || ((keyData & ~Keys.Shift) == Keys.Enter && IsDroppedDown);
}
}
但是,TextBox
使用实现自动完成,这会自动在后台创建一个。无法访问该对象,因此,无法创建我在IsInputKey
中使用的IsDroppedDown
属性。它将使用实现,但由于该对象不可访问,因此您可以无法(可靠地)确定是否显示下拉列表
您需要在不使用内置的AutoComplete*
属性的情况下实现自动完成,或者您需要始终抑制Enter键(删除上述IsInputKey
中的&&IsDroppedDown
)
更新:以下是如何手动创建iautomplete
对象。字符串管理员和职员是硬编码的。GetDropDownStatus函数用于在下拉列表可见时禁止任何默认按钮对Enter的处理。欢迎反馈
iautomplete.cs:
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
[ComImport]
[Guid("00bb2762-6a77-11d0-a535-00c04fd7d062")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[CoClass(typeof(IAutoCompleteClass))]
interface IAutoComplete
{
void Init(HandleRef hwndEdit, IEnumString punkACL, string pwszRegKeyPath, string pwszQuickComplete);
void Enable(bool fEnable);
}
iautomplete2.cs:
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
[Guid("EAC04BC0-3791-11d2-BB95-0060977B464C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAutoComplete2
{
void Init(HandleRef hwndEdit, IEnumString punkACL, string pwszRegKeyPath, string pwszQuickComplete);
void Enable(bool fEnable);
void SetOptions(AutoCompleteOptions dwFlag);
AutoCompleteOptions GetOptions();
};
AutoCompleteOptions.cs:
using System;
[Flags]
enum AutoCompleteOptions : int
{
None = 0x00,
AutoSuggest = 0x01,
AutoAppend = 0x02,
Search = 0x04,
FilterPrefixes = 0x08,
UseTab = 0x10,
UpDownKeyDropsList = 0x20,
RtlReading = 0x40,
WordFilter = 0x80,
NoPrefixFiltering = 0x100,
}
iautompletedropdown.cs:
using System;
using System.Runtime.InteropServices;
using System.Text;
[Guid("3CD141F4-3C6A-11d2-BCAA-00C04FD929DB")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAutoCompleteDropDown
{
void GetDropDownStatus(out AutoCompleteDropDownFlags dwFlags, out StringBuilder wszString);
void ResetEnumerator();
}
AutoCompleteDropDownFlags.cs:
using System;
[Flags]
enum AutoCompleteDropDownFlags : int
{
None = 0x00,
Visible = 0x01
}
iautompleteclass.cs:
using System;
using System.Runtime.InteropServices;
[ComImport]
[Guid("00BB2763-6A77-11D0-A535-00C04FD7D062")]
class IAutoCompleteClass
{
}
EnumString.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
class EnumString : IEnumString
{
const int E_INVALIDARG = unchecked((int)0x80070057);
const int S_OK = 0;
const int S_FALSE = 1;
int current;
string[] strings;
public EnumString(IEnumerable<string> strings)
{
this.current = 0;
this.strings = strings.ToArray();
}
public void Clone(out IEnumString ppenum)
{
ppenum = new EnumString(strings);
}
public int Next(int celt, string[] rgelt, IntPtr pceltFetched)
{
if (celt < 0)
return E_INVALIDARG;
int num = 0;
while (current < strings.Length && celt != 0)
{
rgelt[num] = strings[current];
current++;
num++;
celt--;
}
if (pceltFetched != IntPtr.Zero)
Marshal.WriteInt32(pceltFetched, num);
if (celt != 0)
return S_FALSE;
return S_OK;
}
public void Reset()
{
current = 0;
}
public int Skip(int celt)
{
if (celt < 0)
return E_INVALIDARG;
if (strings.Length - current > celt)
{
current = strings.Length;
return S_FALSE;
}
current += celt;
return S_OK;
}
}
试试这个。希望当你的注意力集中在txtUsername或其他地方时,按enter键不会引起任何问题 如果在
txtexername
中写入a
并按enter键,则将使用正则表达式从autocompletecustomsource
中选择administrator
,焦点将转到txtPassword
private void mainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode.Equals(Keys.Enter))// && !txtUserName.Focus())// && intFlag.Equals(0))
{
if (txtUserName.Text.Length > 0)
{
if (txtUserName.Focused)
{
Regex rg = new Regex(txtUserName.Text, RegexOptions.IgnoreCase);
for (int i = 0; i < txtUserName.AutoCompleteCustomSource.Count; i++)
{
if (rg.IsMatch(txtUserName.AutoCompleteCustomSource[i]))
{
txtUserName.Text = txtUserName.AutoCompleteCustomSource[i];
txtPassword.Focus();
return;
}
}
}
if (txtPassword.Text.Length > 0)
{
btnLogin_Click(null, null); //login
}
else
{
//MessageBox.Show("Please Give a Password");
txtPassword.Focus();
}
}
else
{
//MessageBox.Show("Please Give a username");
txtUserName.Focus();
}
}
//if (txtPassword.ContainsFocus)
//{
// btnLogin_Click(sender, e); //login
//}
//else
//{
// this.txtPassword.Focus();
//}
}