Change Cursor to Square when Combobox text is selected - c#

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;
}
}

Related

Combobox passed as a Control template then as a popup

I have a combobox "recent_users" as a control template and then as a poppup. How can I pass the selected value of the popup to the method below?(popup click)
recent_users.SelectedItem.ToString() always returns null.
private void usernameEnter_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
Trace.WriteLine("testing dropdown");
ControlTemplate ct = recent_users.Template;
Popup popup1 = ct.FindName("PART_Popup", recent_users) as Popup;
if (popup1 != null)
{
popup1.Placement = PlacementMode.Top;
}
recent_users.IsDropDownOpen = true;
popup1.PreviewMouseUp += new MouseButtonEventHandler((s,e) => popupClick(s,e,recent_users.SelectedItem.ToString()));
}
private void popupClick(object sender, MouseButtonEventArgs e, String recent)
{
usernameEnter.Text = recent;
Trace.WriteLine("appending norms");
}
}
}
Isn't it because the user has not made any selection in the ComboBox? I have re-written the code slightly
private void usernameEnter_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
ControlTemplate ct = recent_users.Template;
Popup popup1 = ct.FindName("PART_Popup", recent_users) as Popup;
if (popup1 != null)
{
popup1.Placement = PlacementMode.Top;
}
recent_users.IsDropDownOpen = true;
// if none selected, set first as selected
if (recent_users.SelectedIndex < 0 && recent_users.HasItems)
{
recent_users.SelectedIndex = 0;
}
var selectedItem = recent_users.SelectedItem as ComboBoxItem;
var selectedUser = selectedItem.Content.ToString();
popup1.PreviewMouseUp += new MouseButtonEventHandler((s, e) => popupClick(s, e, selectedUser));
}
But I was wondering adding a handler for PreviewMouseUp event (in the last line) is something that you really want. I would have fetched the selected user in the SelectionChanged of the recent_users rather.

What keyboard shortcut to be used for Mouse Double Click in Sendkeys.Send()

I need to double click the Masked Textbox which is inside datagridview.
But when i try to enter some value after the masked textbox gets focus, I am not able to enter any value. But I can able to enter a value when i double click using mouse. So i checked by writing SendKeys.Send("{F2}") in DataGridView.KeyPress event which works for all the normal columns to edit(like textbox), but not able to enter a value in MaskedTextBox.
Please assist me on the SendKeys.Send() for mouse double click.
In the DataGridView, key press event tried to call sendKeys.send("{F2}").
sendKeys.send("{F2}")
When the Masked textbox inside datagridview comes to focus, user should be able to enter a value.
Below is my sample coding :
private void Form7_Load(object sender, EventArgs e)
{
DataGridViewComboBoxColumn TpyeCol = new DataGridViewComboBoxColumn();
TpyeCol.Name = "Type";
TpyeCol.HeaderText = "Type";
TpyeCol.Items.AddRange(new string[] { "Home Phone", "Cell", "Work", "Email" });
this.dataGridView1.Columns.Add(TpyeCol);
this.dataGridView1.Columns.Add("Description", "Description");
this.dataGridView1.Rows.Add("Home Phone","");
this.maskedTextBox = new MaskedTextBox();
this.maskedTextBox.Visible = false;
this.dataGridView1.Controls.Add(this.maskedTextBox);
this.dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
this.dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
this.dataGridView1.Scroll += new ScrollEventHandler(dataGridView1_Scroll);
}
void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
if (this.maskedTextBox.Visible)
{
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle( this.dataGridView1.CurrentCell.ColumnIndex, this.dataGridView1.CurrentCell.RowIndex, true);
this.maskedTextBox.Location = rect.Location;
}
}
void dataGridView1_CellBeginEdit(object sender,DataGridViewCellCancelEventArgs e)
{
if (e.ColumnIndex == this.dataGridView1.Columns["Description"].Index &&
e.RowIndex < this.dataGridView1.NewRowIndex)
{
string type = this.dataGridView1["Type",e.RowIndex].Value.ToString();
if (type == "Home Phone" || type == "Cell" || type == "Work")
{
this.maskedTextBox.Mask = "00/00/0000";
Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex,e.RowIndex,true);
this.maskedTextBox.Location = rect.Location;
this.maskedTextBox.Size = rect.Size;
this.maskedTextBox.Text = "04/02/2019";
if (this.dataGridView1[e.ColumnIndex, e.RowIndex].Value != null)
{
this.maskedTextBox.Text = this.dataGridView1[e.ColumnIndex,
e.RowIndex].Value.ToString();
}
this.maskedTextBox.Visible = true;
}
}
}
void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (this.maskedTextBox.Visible)
{
this.dataGridView1.CurrentCell.Value = this.maskedTextBox.Text;
this.maskedTextBox.Visible = false;
}
}
void dataGridView1_KeyPress(object sender, DataGridKeyPressEventArgs e)
{
If(dataGridView1.ColumnIndex = 1)
{
SendKeys.Send("{F2}") //To Point cursor in position 1 of Masked TextBox but not able to edit the masked textbox in DGV
}
}
MaskedTextBox maskedTextBox;

Set the Caret/Cursor position in C# WPF when textbox clicked on

I am using a textbox for a login window. I want the textbox to display "Username" in light grey so the user knows to use that box to type in the username. Whenever the user clicks on the textbox even if it's in the middle of the word username I want the cursor to go to the first position and username will disappear when they start typing. I tried using the PreviewMouseDown event but it only works inside breakpoints but doesn't trigger at all outside it. Using the PreviewMouseUp event it works, but other caret positions can be selected before the cursor jumps to the beginning. I want it to appear like the user is unable to select any cursor position besides the first. This is the code I've tried.
private bool textboxuserfirstchange = true;
private void eventTextChanged(object sender, TextChangedEventArgs e)
{
if (textBoxUser.Text != "Username")
{
if (textboxuserfirstchange)
{
textBoxUser.Text = textBoxUser.Text[0].ToString();
textBoxUser.SelectionStart = 1;
textBoxUser.Opacity = 100;
}
textboxuserfirstchange = false;
}
}
private void eventPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
if (textboxuserfirstchange)
{
textBoxUser.Focus();
textBoxUser.Select(0, 0); //None of these working
textBoxUser.SelectionStart = 0;
textBoxUser.CaretIndex = 0;
}
}
You could for example handle the GotKeyboardFocus and PreviewTextInput event. Something like this:
private const string Watermark = "Username";
private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
if (textBoxUser.Text == Watermark)
textBoxUser.Dispatcher.BeginInvoke(new Action(() => textBoxUser.CaretIndex = 0), DispatcherPriority.Background);
}
private void textBoxUser_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (textBoxUser.Text == Watermark)
textBoxUser.Text = string.Empty;
}

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.

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).

Categories