您仍然可以使用 KeyPreview 属性,但检查哪个控件被聚焦,如果它是一个文本框则什么也不做,否则如果它是另一个控件 - 比如 RichTextBox - 然后处理按下的键。要获得当前集中的控制,您可能需要访问 Win32 API。示例:新建一个 Windows 窗体应用程序,在窗体中添加一个文本框和一个富文本框,将窗体的 KeyPreview 属性设置为 true,为窗体、文本框和富文本框的 KeyDown 事件添加事件处理程序。还有以下 using 语句:
using System.Runtime.InteropServices;//for DllImport
然后将表单的代码替换为以下代码:
public partial class Form1 : Form
{
// Import GetFocus() from user32.dll
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)]
internal static extern IntPtr GetFocus();
protected Control GetFocusControl()
{
Control focusControl = null;
IntPtr focusHandle = GetFocus();
if (focusHandle != IntPtr.Zero)
// returns null if handle is not to a .NET control
focusControl = Control.FromHandle(focusHandle);
return focusControl;
}
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
Control focusedControl = GetFocusControl();
if (focusedControl != null && !(focusedControl is TextBox) && e.Control && e.KeyCode == Keys.C)//not a textbox and Copy
{
MessageBox.Show("@Form");
e.Handled = true;
}
}
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.Control && e.KeyCode == Keys.C)
MessageBox.Show("@Control");
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
MessageBox.Show("@Control");
}
}