C# 在Windows窗体中手动设置光标时发出错误声音

C# 在Windows窗体中手动设置光标时发出错误声音,c#,visual-studio,C#,Visual Studio,我是C语言的初学者,我制作了下面的GUI屏幕截图。在这里,用户可以输入一个ID。然后,用户按enter键,光标将自动定位在带有红方块的单元格中。此时程序工作正常。但是,当光标从文本框移动到datagrid视图时,会听到一个声音,好像它是一个错误 因此,我想消除这种声音,我使用的代码如下所示。如果有人能帮助我,我将不胜感激 private void Form1_Load(object sender, EventArgs e) { dataGridView1_Konfigurati

我是C语言的初学者,我制作了下面的GUI屏幕截图。在这里,用户可以输入一个ID。然后,用户按enter键,光标将自动定位在带有红方块的单元格中。此时程序工作正常。但是,当光标从文本框移动到datagrid视图时,会听到一个声音,好像它是一个错误

因此,我想消除这种声音,我使用的代码如下所示。如果有人能帮助我,我将不胜感激

private void Form1_Load(object sender, EventArgs e) {

        dataGridView1_Konfiguration();
        //txtPerson => ID texteditor
        txtPerson.Focus();
        txtPerson.SelectionStart = txtPerson.Text.Length;

}

private void txtPerson_KeyPress(object sender, KeyPressEventArgs e){

        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)){    
                e.Handled = true;
        }
}


private void txtPerson_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter && txtPerson.Text == ""){

           MessageBox.Show("Bitte geben ein gültige Personalnummer !!");
        }
        else if (e.KeyCode == Keys.Enter && txtPerson.Text != ""){

           dataGridView1.Enabled = true;
           dataGridView1.Focus();
           dataGridView1.Rows[0].Cells[1].Selected = true;
    }
}

如果您创建了一个空的WinForms项目,其中只有一个文本框,而没有其他内容,那么当您按enter键时,仍然会听到这种声音。我认为这与Form.AcceptButton属性以及事件路由的位置有关,但我不确定

在您的情况下,要消除声音,您只需在切换到单元后停止对输入事件的进一步处理。你可以把这个

 e.SuppressKeyPress = true;
在txtPerson\u键控处理程序中

整个代码片段的结果如下所示:

    private void txtPerson_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter && txtPerson.Text == "")
        {

            MessageBox.Show("Bitte geben ein gültige Personalnummer !!");
        }
        else if (e.KeyCode == Keys.Enter && txtPerson.Text != "")
        {

            dataGridView1.Enabled = true;
            dataGridView1.Focus();
            dataGridView1.Rows[0].Cells[1].Selected = true;
            e.SuppressKeyPress = true;
        }
    }

我希望这有帮助

我的问题不是如何设置鼠标光标的位置,因为它正在工作!!!为什么我会有这种声音,请阅读之前对问题的描述!!你知道声音在代码中的哪个点出现吗?