WPF TextBox select all on Tab focus - c#

I'm trying to select all the text when the focus is done with the Tab key. But I'm not able to find the right solution. Now I'm using the GotFocusEvent but now when i click with the mouse it raises the event.
The code that I'm using now is:
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new RoutedEventHandler(SelectAllText));
void SelectAllText(object sender, RoutedEventArgs e)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null)
if (!textBox.IsReadOnly)
textBox.SelectAll();
}

Referencing this answer
Textbox SelectAll on tab but not mouse click
What you have can be modified to...
EventManager.RegisterClassHandler(typeof(System.Windows.Controls.TextBox), System.Windows.Controls.TextBox.GotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnGotKeyboardFocus));
void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null && !textBox.IsReadOnly && e.KeyboardDevice.IsKeyDown(Key.Tab))
textBox.SelectAll();
}
You should also take notice of the details about clearing the selection on LostKeyboardFocus

Use MouseButtonState as below:
void SelectAllText(object sender, RoutedEventArgs e)
{
if (Mouse.LeftButton == MouseButtonState.Released)
{
var textBox = sender as System.Windows.Controls.TextBox;
if (textBox != null)
if (!textBox.IsReadOnly)
textBox.SelectAll();
}
}

Related

How to regain focus in application after drag and drop to grid

In my application, I have a form with two panels. Inside one panel is a button. Inside the other is a DevExpress Grid control. The grid is made up of 3 columns. You can drag values from one column into the other to copy it.
My problem is that whenever I do a drag-and-drop from one column to another, the focus on the application goes into an unusual state. The grid remains focused; I can mouse over the headers and see them react as normal. However the rest of the application is not focused. Mouse over the button in the other panel does not react, nor do the menus or form controls. If I click on the button, it reacts like I clicked on an unfocused application. I have to click again to actually activate the button. Same for every control except the grid.
I have tried using Activate() and Focus() on the button and form but to no avail.
namespace Company.StuffUploader
{
public partial class ComputationGrid : DevExpress.XtraEditors.XtraUserControl
{
private BindingList<ComputationLinkModel> _links = new BindingList<ComputationLinkModel>();
public List<ComputationLinkModel> ComputationLinkModels
{
get
{
return new List<ComputationLinkModel>(_links);
}
}
public ComputationGrid()
{
InitializeComponent();
}
private void ComputationGrid_Load(object sender, EventArgs e)
{
_gridControl.DataSource = _links;
}
private DragDropEffects GetDragEffect(DragEventArgs e)
{
var text = e.Data.GetData("System.String") as string;
if (text == null)
return DragDropEffects.None;
var link = GetLinkFromScreenPoint(new Point(e.X, e.Y));
if (link == null)
return DragDropEffects.None;
var tokens = text.Split('\t');
if (tokens.Count() != 2)
return DragDropEffects.None;
var dateString = link.movedate.ToString("yyyy-MM-dd");
if (link.StuffSurfaceName == tokens[0] && dateString != tokens[1])
return DragDropEffects.Move;
else
return DragDropEffects.None;
}
private ComputationLinkModel GetLinkFromScreenPoint(Point screenPt)
{
var pt = _gridControl.PointToClient(screenPt);
var hitInfo = _gridView.CalcHitInfo(pt);
return _gridView.GetRow(hitInfo.RowHandle) as ComputationLinkModel;
}
private void _gridControl_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
var hitInfo = _gridView.CalcHitInfo(e.Location);
if (hitInfo == null || !hitInfo.InRowCell)
return;
// Only allow dragging from target column
if (hitInfo.Column.AbsoluteIndex != 0)
return;
var link = _gridView.GetRow(hitInfo.RowHandle) as ComputationLinkModel;
if (link == null)
return;
var item = string.Format("{0}\t{1}", link.StuffSurfaceName, link.movedate.ToString("yyyy-MM-dd"));
DoDragDrop(item, DragDropEffects.Move);
}
}
private void _gridControl_DragOver(object sender, DragEventArgs e)
{
e.Effect = GetDragEffect(e);
}
private void _gridControl_DragDrop(object sender, DragEventArgs e)
{
}
private void _gridControl_DragEnter(object sender, DragEventArgs e)
{
e.Effect = GetDragEffect(e);
}
private void _unlinkButton_Click(object sender, EventArgs e)
{
}
}
}
I figured out my own problem. Calling DoDragDrop() from within MouseDown event does not seem to work correctly. The proper way is to call it from MouseMove(). The documentation on MSDN hints at this in its example code.
Ensure that you set the DXMouseEventArgs.Handled property to true in the GridView's Mouse~ event handlers. It guarantees that default handling of these events will be prohibited. Review this example to see how to do this.

Change Cursor to Square when Combobox text is selected

I have Editable Combobox in WPF,way it should work is, if text is selected(highlighted), cursor should turn into cross so user can know he can move text into another Combobox, and if user try yo edit cursor should be edit cursor.
Here is code I am trying right now, onFocus Event,
private void LocationComboBox_GotFocus(object sender, RoutedEventArgs e)
{
ComboBox combo = (System.Windows.Controls.ComboBox)sender;
var edit = (TextBox)combo.Template.FindName("PART_EditableTextBox", combo);
var selectedText = edit.SelectedText;
if (!string.IsNullOrEmpty(selectedText))
{
Cursor = Cursors.Cross;
}
else
{
Cursor = Cursors.Arrow;
}
}
here is screen shot
As in Snap, since Austin,TX is highlighted, my cursor should be cross!
Thank you in advance!
Use following code:
private void cmb_Loaded(object sender, RoutedEventArgs e)
{
TextBox TxtBox = (TextBox)cmb.Template.FindName("PART_EditableTextBox", cmb);
if (TxtBox != null)
{
TxtBox.SelectionChanged += TxtBox_SelectionChanged;
}
}
void TxtBox_SelectionChanged(object sender, RoutedEventArgs e)
{
var TxtBox = sender as TextBox;
if (TxtBox != null && !string.IsNullOrEmpty(TxtBox.SelectedText))
{
Mouse.OverrideCursor = Cursors.Cross;
}
else
{
Mouse.OverrideCursor = Cursors.Arrow;
}
}

Button BackColor doesn't change

I want to change my button's color when it has a default color. I tried with code that in below but it doesn't work. How can I do that?
public void ClickedButton (object sender, EventArgs e)
{
if ((sender as Button).BackColor == System.Drawing.SystemColors.Control) {
(sender as Button).BackColor = Color.Turquoise;
}
}
You need to add debug line to verify the current color of the button
public void ClickedButton (object sender, EventArgs e)
{
// add debug line here
string message = (sender as Button).BackColor.ToString();
Debug.WriteLine(message);
if ((sender as Button).BackColor == System.Drawing.SystemColors.Control) {
(sender as Button).BackColor = Color.Turquoise;
}
}
That will help with your troubleshooting of code. Also there is nothing wrong with your current code. Below is the result.
Here is result in the Output Window:
Try casting the sender to a Button first:
public void ClickedButton (object sender, EventArgs e)
{
var btn = sender as Button;
if ((btn != null) && btn.BackColor == System.Drawing.SystemColors.Control)) {
btn.BackColor = Color.Turquoise;
}
}
If this is a Windows Form control, that should work.
If this is a Web Form control, it may not (unless you are calling it as part of a postback).

How to make visible another combo box on selection of a value in current combo box?

I have a combobox(CB1) and it contains items like 1,2,3 and i want to make another combobox (CB2) visible when i select the value 3 from CB1. Which property should i user. I am working on a windows based application and I am using C# as the code behind language. An example would be great to solve the problem.
The combo box CBFormat consists of a list of items as follows:
var allWiegandFormat = WiegandConfigManager.RetrieveAllWiegandFormats();
var allWiegandList = new List<IWiegand>(allWiegandFormat);
CBFormat.Items.Add(allWiegandList[0].Id);
CBFormat.Items.Add(allWiegandList[3].Id);
CBFormat.Items.Add(allWiegandList[4].Id);
CBFormat.Items.Add(allWiegandList[5].Id);
CBProxCardMode.Items.Add(ProxCardMode.Three);
CBProxCardMode.Items.Add(ProxCardMode.Five);
Now I want to show the Combo box of CBPorxCardMode when i select the second item from CBFormat combo box.
Try this
Private void CB1_SelectedIndexChanged(object sender, System.EventArgs e)
{
Combobox CB = (ComboBox) sender;
if(CB.SelectedIndex != -1)
{
int x = Convert.ToInt32(CB.Text)
if(x == 3)
{
CB2.Visible = True;
}
}
}
Use SelectionChangeCommitted event and subscribe your CB1 to it:
// In form load or form initialization
cb1.SelectionChangeCommitted += ComboBoxSelectionChangeCommitted;
// Event
private void ComboBoxSelectionChangeCommitted(object sender, EventArgs e)
{
cb2.Visible = cb1.SelectedItem != null && cb1.Text == "3";
}
If it is Winforms You can use Something Like this
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add(1);
comboBox1.Items.Add(2);
comboBox1.Items.Add(3);
comboBox2.Visible = false;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "3")
{
comboBox2.Visible = true;
}
else
{
comboBox2.Visible = false;
}
}
Hope this helps.,
Start with the CB2 Visible property set to False and add a event handler code for the SelectedIndexChanged on the CB1 through the WinForms designer
private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
ComboBox comboBox = (ComboBox) sender;
if(comboBox.SelectedItem != null)
{
int id = Convert.ToInt32(comboBox.SelectedItem)
cbo2.Visible = (id == 3)
}
}
This is supposing the ID, that you are adding at the first combo, is an Integer value as it seems.
Also rembember that SelectedIndexChanged event will be called even if you change the SelectedItem programmatically and not just when the user changes the value. Also, if the user change again the selection moving away from the ID==3 the method will set again the Cbo2 not visible.

Display column in DataGridView as password input type

I would like to display a column in a datagridview as a column which contains password chars.I cannot figure it out why does this event is not triggered by the datagridview.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if(e.ColumnIndex == 3)
{
if(e.Value != null)
{
e.Value = new string('*', e.Value.ToString().Length);
}
}
}
Help please.
You can handle the EditingControlShowing event and then cast the editing control to a TextBox and manually set the UseSystemPasswordChar to true.
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
if(e.ColumnIndex == 3)//select target column
{
TextBox textBox = e.Control as TextBox;
if (textBox != null)
{
textBox.UseSystemPasswordChar = true;
}
}
}

Categories