问题
I placed a RichTextBox control on a new form and launched the project. So the RichTextBox.Text = "";
Each time I press Up or Down keys I heard the annoying BEEP sound! How to get rid of this issue?
Using "e.SuppressKeyPress = true" in the KeyDown method locks the Cursor position.
回答1:
Well, you can try suppressing the key only if the caret is on the first line and the key is up, or on the last line and the key is down or in position 0 and the key is left, etc.
That said, this is how most textboxes behave, and the sound is set in your operating system preferences. You'd get the same beep in, say, Wordpad or Outlook, if you try to move the caret beyond the limit of a textbox.
回答2:
first we need send EM_GETOLEINTERFACE message to rich edit window - this is Retrieves an IRichEditOle object that a client can use to access a rich edit control's Component Object Model (COM) functionality.
then for retrieve an ITextServices pointer, call QueryInterface
on the private IUnknown
pointer returned by EM_GETOLEINTERFACE.
here exist interesting point - the IID_ITextServices
not well known but need get in runtime from Msftedit.dll
from About Windowless Rich Edit Controls
Msftedit.dll exports an interface identifier (IID) called IID_ITextServices that you can use to query the IUnknown pointer for the ITextServices interface.
after we got ITextServices pointer - we simply can call OnTxPropertyBitsChange(TXTBIT_ALLOWBEEP, 0)
code example:
if (HMODULE hmodRichEdit = LoadLibrary(L"Msftedit.dll"))
{
// create richedit window
if (HWND hwndRich = CreateWindowExW(0, MSFTEDIT_CLASS, ...))
{
if (IID* pIID_ITS = (IID*) GetProcAddress(hmodRichEdit, "IID_ITextServices"))
{
IUnknown* pUnk;
if (SendMessageW(hwndRich, EM_GETOLEINTERFACE, 0, (LPARAM)&pUnk))
{
ITextServices* pTxtSrv;
HRESULT hr = pUnk->QueryInterface(*pIID_ITS, (void**)&pTxtSrv);
pUnk->Release();
if (0 <= hr)
{
pTxtSrv->OnTxPropertyBitsChange(TXTBIT_ALLOWBEEP, 0);
pTxtSrv->Release();
}
}
}
}
}
回答3:
This code below should stop the beeping sound, and works with wrapped and unwrapped text:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
if (
richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart) == 0 && e.KeyData == Keys.Up ||
richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart) == richTextBox1.GetLineFromCharIndex(richTextBox1.TextLength) && e.KeyData == Keys.Down ||
richTextBox1.SelectionStart == richTextBox1.TextLength && e.KeyData == Keys.Right ||
richTextBox1.SelectionStart == 0 && e.KeyData == Keys.Left
) e.Handled = true;
}
来源:https://stackoverflow.com/questions/4683663/how-to-remove-annoying-beep-with-richtextbox