windows 表单应用程序中的应用程序内部未检测到 Sendkeys 事件

Sendkeys event is not detected inside the application in windows form application

我是 windows 应用程序开发的新手。我正在开发一个 Windows 表单应用程序,其布局如下:

有一个文本框,我使用 SendKeys 事件在应用程序中创建了键盘。

问题是系统上的所有其他应用程序都能检测到按键,但应用程序内的文本框无法检测到按键。

基本上应用程序有完整的键盘这只是一个按钮按下代码

我尝试过的:

public partial class Form1 : Form
{
    Control focusedC;
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams param = base.CreateParams;
            param.ExStyle |= 0x08000000;
            return param;
        }
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        FormBorderStyle = FormBorderStyle.None;
        WindowState = FormWindowState.Maximized;
        TopMost = true;
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Escape) {
            FormBorderStyle = FormBorderStyle.Sizable;
            WindowState = FormWindowState.Normal;
            TopMost = false;
        }
    }

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        //checkbox is for CapsLock Key
    }

    private void button14_Click(object sender, EventArgs e)
    {
        if (checkBox1.Checked && focusedC != null)
        {
            focusedC.Focus();
            SendKeys.Send("Q");
        }
        else if(focusedC != null)
        {
            focusedC.Focus();
            SendKeys.Send("q");
        }
    }
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        focusedC = sender as TextBox;
    }
}

对于 WPF 应用程序,您必须使用 SendKeys.SendWait() method.

SendKeys.SendWait("Q")

SendKeys.Send() 将适用于 WinForm 应用程序。

另一种选择是使用 WinAPI 而不是 SendKeys。更多信息 here

编辑 1

Control focusedC;

//Enter event handler for your TextBox

private void textBox1_TextChanged(object sender, EventArgs e)
{
    focusedC = sender as TextBox;
}

//Click event handler 
private void  button14_Click(object sender, EventArgs e)
{
    if (focusedC != null)
    {
        focusedC.Focus();
        SendKeys.Send("Q");
    }
}

编辑 2:使用 WinAPI

[DllImport("user32.dll")]
static extern void SendInput(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);
  public static void PressKey(byte keyCode)
    {
        const int KEYEVENTF_EXTENDEDKEY = 0x1;
        const int KEYEVENTF_KEYUP = 0x2;
        SendInput((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
        SendInput((byte)keyCode, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);

    }

调用PressKey函数使用,Keycodes可查here

当然,它不适用于您的 window。你设置的是WS_EX_NOACTIVATE风格!它适用于其他 windows 但显然不适用于您的。如果你想让它在你的文本框上工作,请删除或评论这一行

param.ExStyle |= 0x08000000;

它会在您的应用程序中正常工作 window 其他人:

private void button14_Click(object sender, EventArgs e)
{
    if (checkBox1.Checked)
    {
        textBox1.Focus();
        SendKeys.Send("Q");
    }
    else
    {
        textBox1.Focus();
        SendKeys.Send("q");
    }
}