Prevent selecting text in a TextBox - c#

Similar questions have been already asked (e.g., here), however I've not found an answer for my specific case. I'm building a custom control based on a DevExpress control, which in turns is based on standard TextBox and I've a flickering problem that seems due to the base TextBox component, which tries to update selection.
Without explaining all the details of my custom control, to reproduce the problem you just need to place a TextBox inside a Form and then use this code:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
textBox1.MouseMove += TextBox1_MouseMove;
}
private void TextBox1_MouseMove(object sender, MouseEventArgs e) {
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
}
}
If you launch it, you click on the TextBox and then you move the cursor toward right you will notice the flickering problem (see video here). For my custom control I would need to avoid this flickering. I'm bound to use a TextBox (so no RichTextBox). Any idea?

The solution has been provided in the meantime by Reza Aghaei by overriding WndProc and intercepting WM_SETFOCUS messages. See here

Depending on what u want to do there are several solutions:
If you want to prevent the selection it would be:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
(sender as TextBox).SelectionLength = 0;
}
Or for selecting all:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
(sender as TextBox).SelectAll();
}
And besides that u also could specify the conditions for selecting, for example:
private void TextBox1_MouseMove(object sender, MouseEventArgs e)
{
(sender as TextBox).Text = DateTime.Now.Ticks.ToString();
if (MouseButtons == MouseButtons.Left) (sender as TextBox).SelectAll();
else (sender as TextBox).SelectionLength = 0;
}
But as long as you want to select the text you always will get some flickering, because a normal Textbox has not the possibility to use things like BeginEdit and EndEdit and so it will change the text first and then select it.

Looking at the video it looks like your textbox is calling WM_ERASEBKGND unnecessarily. In order to remedy this problem you can subclass the textbox class and intercept these messages. Below is sample code which should do the trick (untested) Disclaimer: I have used this technique for other WinForm controls that had the type of flicker shown in your video but not TextBox. If it does work for you, please let me know. Good luck!
// textbox no flicker
public partial class TexttBoxNF : TextBox
{
public TexttBoxNF()
{
}
public TexttBoxNF(IContainer container)
{
container.Add(this);
InitializeComponent();
//Activate double buffering
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);
//Enable the OnNotifyMessage event so we get a chance to filter out
// Windows messages before they get to the form's WndProc
this.SetStyle(ControlStyles.EnableNotifyMessage, true);
}
//http://stackoverflow.com/questions/442817/c-sharp-flickering-listview-on-update
protected override void OnNotifyMessage(Message m)
{
//Filter out the WM_ERASEBKGND message
if (m.Msg != 0x14)
{
base.OnNotifyMessage(m);
}
}
}

Related

TextBox took back focus while other controls don't

I wanted to focus to a TextBox when I leave an other TextBox.
Let's say I have 3 textboxes. The focus is in the first one, and when I click into the second one, I want to put the focus into the last one instead.
I subscribed to the first textbox's Leave event and tried to focus to the third textbox like: third.Focus(). It gains focus for a moment but then the second one got it eventually (the one I clicked).
Strangely if I replace the second TextBox to a MaskedTextBox (or to any other control), the focus remains on the third one.
Pressing Tab does work though.
These are plain textboxes right from the toolbox.
What is the reason, how can I solve this?
Try to handle Enter event of the textBox2. (In properties window double click on Enter event)
//From Form1.Designer.cs
this.textBox2.Enter += new System.EventHandler(this.textBox2_Enter);
private void textBox2_Enter(object sender, EventArgs e)
{
textBox3.Focus();
}
EDIT:
This code looks very strange, but it works for me. According to this post HERE I use ActiveControl property instead of Focus() method. But behavior of TextBox is very strange because it try to be focused multiple times.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
foreach (Control control in Controls)
{
control.LostFocus += (s, e) => Console.WriteLine(control.Name + " LostFocus");
control.GotFocus += (s, e) =>
{
Console.WriteLine(control.Name + " GotFocus");
if (!requestedFocusToTextBox2) return;
ActiveControl = textBox2; //textBox2.Focus() doesn't work
requestedFocusToTextBox2 = false;
};
}
}
private bool requestedFocusToTextBox2;
private void textBox1_Leave(object sender, EventArgs e)
{
ActiveControl = textBox2;
requestedFocusToTextBox2 = true;
}
}

C# Apply focused properties to FlowLayoutPanel like button behavior

I'm trying to apply focus behavior, similar to button blue border to FlowLayoutPanel. I tried to use GotFocus and LostFocus, but clearly that's not the way to go.
private void FlowLayoutPanel_Click(object sender, EventArgs e)
{
(sender as Control).BackColor = SystemColors.GradientActiveCaption;
//More operations.
}
private void Panel_LostFocus(object sender, System.EventArgs e)
{
(sender as Control).BackColor = default(Color);
//More operations.
}
While clicking on the FlowLayoutPanel nothing happens and while using tab the two event are invoked one after another.
Any suggestions?
FlowLayoutPanel is not a selectable control by default. You can create a custom flow layout panel by deriving from FlowLayoutPanel and set Selectable and UserMouse control styles to make it selectable by mouse. Also to accept tab stop, set TabStop property to true:
class ExFlowLayoutPanel:FlowLayoutPanel
{
public ExFlowLayoutPanel():base()
{
SetStyle(ControlStyles.Selectable, true);
SetStyle(ControlStyles.UserMouse, true);
TabStop = true;
}
}
Then you can handle GotFocus and LostFocus or Enter and Leave events.
The only point of using a FLP is to get it to arrange child controls. It is always a child control that gets the focus, not the FLP. So sure, nothing happens. You'd have to subscribe the Enter events of all the child controls to see the focus entering the panel or one of its children. Leave is much harder to get right, that's going to flicker like a cheap motel.
Very ugly solution, you don't want to it that way. Use the Application.Idle event instead, the best alternative when getting a reliable event just isn't practical. Check the Parent of this.ActiveControl, like this:
public Form1() {
InitializeComponent();
Application.Idle += CheckFlpFocus;
this.Disposed += delegate { Application.Idle -= CheckFlpFocus; };
}
private bool FlpHasFocus;
private void CheckFlpFocus(object sender, EventArgs e) {
bool hasFocus = false;
for (var ctl = this.ActiveControl; ctl != null; ctl = ctl.Parent) {
if (ctl == flowLayoutPanel1) hasFocus = true;
}
if (hasFocus != FlpHasFocus) {
FlpHasFocus = hasFocus;
flowLayoutPanel1.BackColor = hasFocus ? Color.Black : Color.White;
}
}

Mouse up event doesn't get triggered

I have the following problem: I have a panel which has a specific color, say red.
When the user presses his mouse, the color of this panel gets stored in a variable. Then the user moves, his mouse still pressed, over to another panel. When he releases the mouse there, this panel should get the background color of the first that had been stored in the variable. My code looks something like this:
public Color currentColor;
private void ColorPickMouseDown(object sender, MouseEventArgs e)
{
Panel pnlSender = (Panel)sender;
currentColor = pnlSender.BackColor;
}
private void AttempsColorChanger(object sender, MouseEventArgs e)
{
Panel pnl = (Panel)sender;
pnl.BackColor = currentColor;
}
I need to identify the sender first because there are many possible panels that can trigger this event. The first MouseDown method works totally fine, the color is stored nicely in the variable. The secon one however doesn't even get triggered when the user does what I described above. When the ser clicks on the second panel, it works (there is an MouseUp part in a click aswell I guess).
What's wrong here? Why is the event not triggered when the user holds the mouse key down before?
(This answer assumes you are using Windows Forms.)
It could be that you need to capture the mouse by setting this.Capture = true in the MouseDown of the source control. (See Control.Capture)
If you did that, the source window would get the MouseUp event, and it would be the source window that had to determine the destination window under the mouse coords. You can do that using Control.GetChildAtPoint() (see this answer on Stack Overflow).
Use Windows Forms Drag and Drop Support Instead! <- Click for more info
I'm going to suggest you bite the bullet and use the .Net Drag and Drop methods to do this. It requires some reading up, but it will be much better to use it.
You start a drag in response to a MouseDown event by calling Control.DoDragDrop().
Then you need to handle the Control.DragDrop event in the drop target control.
There's a few more things you might need to do to set it up; see the Control.DoDragDrop() documentation for an example.
(For WPF drag and drop support, see here.)
when your mouse enter the target control , mouse down triggerd ang get target BackColor! you need add an boolean flag to your code :
public Color currentColor;
bool flag=false;
private void ColorPickMouseDown(object sender, MouseEventArgs e)
{
if(flag==false)
{
flag=true
Panel pnlSender = (Panel)sender;
currentColor = pnlSender.BackColor;
}
}
//assume mouse up for panles
private void AttempsColorChanger(object sender, MouseEventArgs e)
{
if(flag==true)
{
Panel pnl = (Panel)sender;
pnl.BackColor = currentColor;
flag=flase;
}
}
and also you need change your flag in mouseMove( if )
As I mentioned in my comment Mouse Events are captured by the originating control, You would probably be better off using the DragDrop functionality built into Windows Forms. Something like this should work for you. I assigned common event handlers, so they can be assigned to all of your panels and just work.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel_MouseDown(object sender, MouseEventArgs e)
{
((Control)sender).DoDragDrop(((Control)sender).BackColor,DragDropEffects.All);
}
private void panel_DragDrop(object sender, DragEventArgs e)
{
((Control)sender).BackColor = (Color)e.Data.GetData(BackColor.GetType());
}
private void panel_DragEnter(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Copy;
}
}
I know it's an old question but I had the same issue and none of the above answers worked for me. In my case I had to handle the MouseMove event in the target control and check for the mouse to be released. I did set 'BringToFront' on my target panel just in case that helped at all.
public Color currentColor;
private void ColorPickMouseDown(object sender, MouseEventArgs e)
{
Panel pnlSender = (Panel)sender;
currentColor = pnlSender.BackColor;
}
private void panelTarget_MouseMove(object sender, MouseEventArgs e)
{
//the mouse button is released
if (SortMouseLocation == Point.Empty)
{
Panel pnl = (Panel)sender;
pnl.BackColor = currentColor;
}
}

Is there a way to set a control as a tooltip?

I'm wondering if it's possible to use ToolTip.SetToolTip or something similar to open a control as a tooltip instead of just a string (i.e. SetToolTip(controlToWhichToAdd, panelToDisplayAsToolTip) instead of passing a string as your second parameter).
If this isn't possible I'm guessing next best thing is displaying a panel on the mouse location on mouse_enter event on the control and removing it (or making it invisible) on mouse_leave.
Or are there other practices that make this possible in an easier way?
This is not possible out of the box. You have two choices. First option is to override the Draw Event, which will let you customize how the tooltip looks. Here is an example of this. Be sure you set the OwnerDraw property to true if you use this method!
Although the first method will work if you just need some simple customization, the second option will work best if you need more flexible options. The second option is to do what you already suggested and create your own sort of tooltip. Simply put, you would first create an event handler for the MouseEnter event. When that event fires, you'd enable a Timer. This timer would be the delay that occurs before the tooltip is show. Then finally, you'd just make your panel appear at the mouse coordinates.
Suppose you have a form with a button and timer on it and you want the button to have a tooltip that is a panel:
public partial class Form1 : Form
{
private Panel _myToolTipPanel;
private void Form1_Load(object sender, EventArgs e)
{
_myToolTipPanel = new Panel {Visible = false};
Controls.Add(_myToolTipPanel);
Label myLabel = new Label();
myLabel.Text = "Testing";
_myToolTipPanel.Controls.Add(myLabel);
}
private void button1_MouseEnter(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void button1_MouseLeave(object sender, EventArgs e)
{
timer1.Enabled = false;
_myToolTipPanel.Visible = false;
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
Point position = Cursor.Position;
Point formPoisition = PointToClient(position);
_myToolTipPanel.Visible = true;
_myToolTipPanel.Location = formPoisition;
}
}
Now of course you will have to do some beautifying of the tooltip, but this is the general idea!
One Approach could be inheriting the ToolTip control and then override the SetToolTip and Show methods . Inside the SetToolTip the private method - SetToolTipInternal needs to be re-written , but most of the functionality could be reuse - it uses the Mouse Events ( leave , move) to bind region. but since tooltip uses internal's of windows to show the baloon window. you will have to override quite a bit of code.
but this could be time consuming and needs quite a bit of testing.
You could write a handler for the Tooltip.Popup event, and cancel the popup to display your own panel.
You'd need to clean it up at the appropriate time, though.
For example:
private void ToolTip1_Popup(Object sender, PopupEventArgs e)
{
e.Cancel = true;
//Do work here to display whatever control you'd like
}
If you're just looking for more formatting options in the tooltip display, an alternative is something like this CodeProject entry, which implements an HTML-enabled tooltip:

How to select all text in Winforms NumericUpDown upon tab in?

When the user tabs into my NumericUpDown I would like all text to be selected. Is this possible?
private void NumericUpDown1_Enter(object sender, EventArgs e)
{
NumericUpDown1.Select(0, NumericUpDown1.Text.Length);
}
(Note that the Text property is hidden in Intellisense, but it's there)
I wanted to add to this for future people who have been search for Tab and Click.
Jon B answer works perfect for Tab but I needed to modify to include click
Below will select the text if you tab in or click in. If you click and you enter the box then it will select the text. If you are already focused on the box then the click will do what it normally does.
bool selectByMouse = false;
private void quickBoxs_Enter(object sender, EventArgs e)
{
NumericUpDown curBox = sender as NumericUpDown;
curBox.Select();
curBox.Select(0, curBox.Text.Length);
if (MouseButtons == MouseButtons.Left)
{
selectByMouse = true;
}
}
private void quickBoxs_MouseDown(object sender, MouseEventArgs e)
{
NumericUpDown curBox = sender as NumericUpDown;
if (selectByMouse)
{
curBox.Select(0, curBox.Text.Length);
selectByMouse = false;
}
}
You can use this for multiple numericUpDown controls. Just need to set the Enter and MouseDown Events
I was looking around i had the same issue and this Works for me, first select the Item and the second one selects the Text, hope it helps in future
myNumericUpDown.Select();
myNumericUpDown.Select(0, myNumericUpDown.Value.ToString().Length);
I created an extension method to accomplish this:
VB:
<Extension()>
Public Sub SelectAll(myNumericUpDown As NumericUpDown)
myNumericUpDown.Select(0, myNumericUpDown.Text.Length)
End Sub
C#:
public static void SelectAll(this NumericUpDown numericUpDown)
numericUpDown.Select(0, myNumericUpDown.Text.Length)
End Sub
I had multiple numericupdown box's and wanted to achieve this for all. I created:
private void num_Enter(object sender, EventArgs e)
{
NumericUpDown box = sender as NumericUpDown;
box.Select();
box.Select(0, num_Shortage.Value.ToString().Length);
}
Then by associating this function with the Enter Event for each box (which I didn't do), my goal was achieved. Took me a while to figure out as I am a beginner. Hope this helps someone else out
For selecting all text by mouse click or by Tab button I use:
public frmMain() {
InitializeComponent();
numericUpDown1.Enter += numericUpDown_SelectAll;
numericUpDown1.MouseUp += numericUpDown_SelectAll;
}
private void numericUpDown_SelectAll(object sender, EventArgs e) {
NumericUpDown box = sender as NumericUpDown;
box.Select(0, box.Value.ToString().Length);
}
Try
myNumericUpDown.Select(0, myNumericUpDown.Value.ToString().Length);

Categories

Resources