Windows Forms手动设置光标时出现错误提示音问题求助
Hey there! I totally get how annoying that random error beep can be when your code works functionally but makes that unwelcome noise. Let's fix this quickly.
Why the Beep Happens
That beep usually pops up because when you press Enter in the TextBox, the system tries to handle the key press with its default behavior (like triggering a form's default button, or treating Enter as invalid input for a single-line TextBox). Even though you're switching focus to the DataGridView, the system still registers that the Enter key's default action wasn't properly handled, so it plays the error tone.
Solution 1: Suppress the Key Press in KeyDown Event
Add this to your TextBox's KeyDown event handler. The key line here is e.SuppressKeyPress = true — it tells the system you've fully handled the Enter key, so it doesn't need to run any default actions (including playing the beep).
private void textBoxId_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { // Your existing logic to set focus to the DataGridView cell dataGridView1.CurrentCell = dataGridView1.Rows[yourTargetRowIndex].Cells[yourTargetColumnIndex]; dataGridView1.Focus(); // Stop the system from processing the Enter key further e.SuppressKeyPress = true; } }
Solution 2: Mark the Event as Handled in KeyPress Event
If you prefer using the KeyPress event instead, you can set e.Handled = true to achieve the same result:
private void textBoxId_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) { // Your cursor positioning logic here dataGridView1.CurrentCell = dataGridView1.Rows[yourTargetRowIndex].Cells[yourTargetColumnIndex]; dataGridView1.Focus(); // Tell the system we've handled this key press e.Handled = true; } }
Either of these should eliminate that pesky beep while keeping your cursor positioning functionality intact. Just make sure you're replacing yourTargetRowIndex and yourTargetColumnIndex with the actual row/column indices of your red-box cell.
内容的提问来源于stack exchange,提问作者Margarita Gonzalez

