Is it possible to disable textbox from selecting part of text through double-click
The default behaviour of doubleclicking in a tex开发者_如何学Ctbox is select part of text. I wanna override it with selecting a word. But I found handling the doubleclick event(or override the OnDoubleClick method) actually do the default behaviour first, then execute my code. Is it possible to disable the default behaviour.
It doesn't look like you can do this with standard WinForms event handlers (DoubleClick
and MouseDoubleClick
don't give you any way to suppress the default behavior), but you can do this by creating a custom WndProc
and handling the window messages yourself.
In the example below, I override the default Control.WndProc
in the PreviewTextBox
class I create. I expose the PreviewDoubleClick
event through this class which, if handled in client code, can be used to suppress the default double-click behavior by setting e.Handled = true;
. In this example, the event is handled in the OnPreviewDoubleClick
event handler, where you can add your custom code to do react to the double-click however you want.
If you need additional mouse information about the double click, I believe you can get that through the Message.LParam
/Message.WParam
fields in the WndProc
.
(the code below assumes you have some code behind for the form already setup)
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
class DoubleClickEventArgs : EventArgs
{
public bool Handled
{
get;
set;
}
}
class PreviewTextBox : TextBox
{
public event EventHandler<DoubleClickEventArgs> PreviewDoubleClick;
protected override void WndProc(ref Message m)
{
if ((m.Msg == WM_DBLCLICK) || (m.Msg == WM_LBUTTONDBLCLK))
{
var e = new DoubleClickEventArgs();
if (PreviewDoubleClick != null)
PreviewDoubleClick(this, e);
if (e.Handled)
return;
}
base.WndProc(ref m);
}
const int WM_DBLCLICK = 0xA3;
const int WM_LBUTTONDBLCLK = 0x203;
}
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
_textBox = new PreviewTextBox();
_textBox.Text = "Test text foo bar";
_textBox.PreviewDoubleClick += new EventHandler<DoubleClickEventArgs>(OnPreviewDoubleClick);
Controls.Add(_textBox);
}
void OnPreviewDoubleClick(object sender, DoubleClickEventArgs e)
{
e.Handled = true;
}
PreviewTextBox _textBox;
}
}
精彩评论