Is it possible to disable a textbox from selecting a piece of text with a double click
The default double-click behavior in a text box is a piece of text. I want to override it by choosing a word. But I found that handling the doubleclick event (or overriding the OnDoubleClick method) actually does the default behavior and then executes my code. Is it possible to disable the default behavior.
a source to share
It doesn't look like you can do this with standard WinForms event handlers ( DoubleClick
and MouseDoubleClick
doesn't give you the ability to suppress the default behavior), but you can do it by creating a custom one WndProc
and handling window messages yourself.
In the example below, I am overriding the default Control.WndProc
in the class PreviewTextBox
I am creating. I expose the event PreviewDoubleClick
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 an event handler OnPreviewDoubleClick
, where you can add your own code to respond to the double click, but you want.
If you need more information on double click I believe you can get it via Message.LParam
/ Message.WParam
in WndProc
.
(the code below assumes you have the code for an already configured form)
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;
}
}
a source to share