Clear MenuItem, with clear command - c#

hi
i'm a "very" beginner in wpf
i'm trying to make a menu item "Clear", it should clear the text in the focused text box,
actually i could not find a built in command that does the job like (copy,paste,cut..etc)
is there one built in or do i have to make a custom routed command, and if so
i've tried but failed, and need ideas
i've made the ClearCommandExecuted logic, but the problem is with "CanExecute"
i tried to access the Keyboard.FocusedElement there, but failed because the focused element is the menu item it self when it's clicked !!!!
please help
thanks

You need to use one of the arguments passed into your CanExecuteQuery:
private void ClearCommandBindingCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
// e.Source is the element that is active,
if (e.Source is TextBox) // and whatever other logic you need.
{
e.CanExecute = true;
e.Handled = true;
}
}
private void ClearCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)
{
var textBox = e.Source as TextBox;
if (textBox != null)
{
textBox.Clear();
e.Handled = true;
}
}
I hope this is enough to get you headed in the right direction...

Try to use the FocusManager class. When your TextBox has lost Keyboard Focus, it still has Logical Focus, if it is inside the Focus Scope. Classes in WPF which are focus scopes by default are Window, MenuItem, ToolBar, and ContextMenu.
So using this will give you the result -
FocusManager.GetFocusedElement(winodw1); //Name of the window
For more details, read this - http://msdn.microsoft.com/en-us/library/aa969768.aspx

Related

Show ToolTip for DataGridView on KeyDown

So I'm looking for a way to display some help when a key is pressed. I'm thinking the best option is ToolTip. But how can I get it so it shows instantly on KeyDown on a DataGridView? I have the ToolTip setup when KeyDownis pressed. However it doesn't show up for some reason. This is the code in my KeyDown event:
if (e.Control)
{
if(tt == null)
{
tt = new ToolTip();
tt.InitialDelay = 0;
tt.Active = true;
tt.Show("Help Test", dataGridView1.FindForm());
}
}
Yet nothing displays when I push down Ctrl.
You should set this.dataGridView1.ShowCellToolTips = false; using designer or using code, then you can show a manual ToolTip.
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if(e.Control)
toolTip1.Show("Some help", this.dataGridView1);
}
Note: You should dispose a ToolTip when the form disposes, so it's better to drop a ToolTip component from toolbox on form and use it. This way you don't need to dispose it manually yourself.

Combobox cancel dropdown

I've got a combobox that opens a new form window with a datagridview, and I want the users to choose the items through that datagridview rather than through the combobox. I've got this code to achieve that:
private void comboBox1_DropDown(object sender, EventArgs e)
{
valSel.incBox = (ComboBox)sender;
valSel.Show();
if (this.comboBox1.DroppedDown)
{
MessageBox.Show("test");
SendMessage(this.comboBox1.Handle, CB_SHOWDROPDOWN, 0, 0);
}
}
As you see I'm also trying to hide the dropdown of the combobox but it isn't working. I assume it's because the combobox hasn't actually "dropped down" yet, so that part of the code is never run.
Is there an event or something I can cell when the combobox has fully "dropped down" so i can send the message to close it again?
You should be able to simply set the height of the ComboBox to something really small. Last time I looked at it, this determined the height of the popup part (the actual height of the control is determined by the UI/font size).
The more elegant way, however, would be using a custom control that just mimics the appearance of dropdown boxes (I'm rather sure that can be done some easy way).
In comboBox1.Enter set the focus to a different control if condition is met.
private void comboBox1_Enter(object sender, EventArgs e)
{
if (comboBox1.Items.Count < 1)
{
comboBox1.DroppedDown = false;
comboBox2.Focus();
MessageBox.Show("Select a list first");
comboBox2.DroppedDown = true;
}
}
1) create a KeyPress event on ComboBox from the properties.
2) write code
private void cmbClientId_KeyPress(object sender, KeyPressEventArgs e)
{
((ComboBox)sender).DroppedDown = false;
}

How can I keep multiple controls in focus?

I have a tree view on the left side. Selecting a node displays relevant information in a form on the right side.
Would I be able to keep the tree and any one control (textbox, combobox, checkbox) on the right in focus at the same time? This will enable a user to select a field, make a change, select another node, and without having to go back and select the same field again, just type and change the value of the same field.
Thanx.
EDIT
I suppose one could implement such behaviour manually:
private Control __cFocus;
private void {anyControl}_Focus(object sender, EventArgs e)
{
__cFocus = (Control)sender;
}
private void treeView1_AfterSelect(object sender, EventArgs e)
{
__cFocus.Focus();
}
I was just wondering if there exists an automatic / more elegant solution
EDIT 2
Ok, so it seems I'll have to implement it manually. Manual implementation it is then. However, now there seem to be another problem; not sure if I should ask this as a separate question.
When selecting a node the textbox gains focus as intended, but only when using the keyboard. It doesn't work when selecting a node with the mouse. First I thought that it might be a mouse event that's interfering, but stepping revealed that the MouseUp event fired first and then the AfterSelect event which sets the focus, so I don't think it's interfering. The textbox's Enter event is also fired, but for some reason it loses focus again to the tree.
Thanx
no, you cannot keep two controls in focus at the same time. But what you can do is set the focus to the target control in the treeview AfterSelect event
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Focus();
textBox1.SelectAll();
}
then in your textbox leave, save the changes, like so:
private void textBox1_Leave(object sender, EventArgs e)
{
//save changes here
}
this way, everytime you select an item in the treeview, check your textbox for change and save as needed, then you will refocus on the textbox for your next edit
There only can be one element having the focus!
But I have an idea for you that might solve your problem. Assuming you have a window with a TreeView and a TextBox. Set the HideSelection property of the TreeView to false and subscribe the AfterSelect event (like edeperson already answered) like this:
private void OnTreeViewAfterSelect(object sender, TreeViewEventArgs e)
{
textBox1.Text = e.Node.Text;
textBox1.Focus();
}
Then subscribe the KeyDown event of the TextBox and do following in the event method:
private void OnTextBoxKeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Up) || (e.KeyCode == Keys.Down))
{
treeView1.Focus();
SendKeys.Send(e.KeyCode == Keys.Up ? "{UP}" : "{DOWN}");
}
}
At last subscribe the Leave event of the TextBox and do following in the event method:
private void OnTextBoxLeave(object sender, EventArgs e)
{
if (treeView1.SelectedNode != null)
{
treeView1.SelectedNode.Text = textBox1.Text;
}
}
And, voilá it should work like you expected it...
If you want to focus on it , you can use usercontrol. you can put your textbox on usercontrol and set focus of this textbox on usercontrol using set properties on treeview select.
No you may not, only one control may be in focus at any given time.
See Moonlight's comment for one way to achieve the behavior that you seek.

How to remove the focus from a TextBox in WinForms?

I need to remove the focus from several TextBoxes. I tried using:
textBox1.Focused = false;
Its ReadOnly property value is true.
I then tried setting the focus on the form, so as to remove it from all the TextBoxes, but this also fails to work:
this.Focus();
and the function returns false when a textbox is selected.
So, how do I remove the focus from a TextBox?
You can add the following code:
this.ActiveControl = null; //this = form
Focusing on the label didn't work for me, doing something like label1.Focus() right?
the textbox still has focus when loading the form, however trying Velociraptors
answer, worked for me, setting the Form's Active control to the label like this:
private void Form1_Load(object sender, EventArgs e)
{
this.ActiveControl = label1;
}
Try disabling and enabling the textbox.
You can also set the forms activecontrol property to null like
ActiveControl = null;
Focus sets the input focus, so setting it to the form won't work because forms don't accept input. Try setting the form's ActiveControl property to a different control. You could also use Select to select a specific control or SelectNextControl to select the next control in the tab order.
Try this one:
First set up tab order.
Then in form load event we can send a tab key press programmatically to application. So that application will give focus to 1st contol in the tab order.
in form load even write this line.
SendKeys.Send("{TAB}");
This did work for me.
This post lead me to do this:
ActiveControl = null;
This allows me to capture all the keyboard input at the top level without other controls going nuts.
A simple solution would be to kill the focus, just create your own class:
public class ViewOnlyTextBox : System.Windows.Forms.TextBox {
// constants for the message sending
const int WM_SETFOCUS = 0x0007;
const int WM_KILLFOCUS = 0x0008;
protected override void WndProc(ref Message m) {
if(m.Msg == WM_SETFOCUS) m.Msg = WM_KILLFOCUS;
base.WndProc (ref m);
}
}
I've found a good alternative! It works best for me, without setting the focus on something else.
Try that:
private void richTextBox_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
}
I made this on my custom control, i done this onFocus()
this.Parent.Focus();
So if texbox focused - it instantly focus textbox parent (form, or panel...)
This is good option if you want to make this on custom control.
It seems that I don't have to set the focus to any other elements. On a Windows Phone 7 application, I've been using the Focus method to unset the Focus of a Textbox.
Giving the following command will set the focus to nothing:
void SearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Focus();
}
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx
It worked for me, but I don't know why didn't it work for you :/
//using System;
//using System.Collections.Generic;
//using System.Linq;
private void Form1_Load(object sender, EventArgs e)
{
FocusOnOtherControl(Controls.Cast<Control>(), button1);
}
private void FocusOnOtherControl<T>(IEnumerable<T> controls, Control focusOnMe) where T : Control
{
foreach (var control in controls)
{
if (control.GetType().Equals(typeof(TextBox)))
{
control.TabStop = false;
control.LostFocus += new EventHandler((object sender, EventArgs e) =>
{
focusOnMe.Focus();
});
}
}
}
The way I get around it is to place all my winform controls. I make all labels and non-selecting winform controls as tab order 0, then my first control as tab order 2 and then increment each selectable control's order by 1, so 3, 4, 5 etc...
This way, when my Winforms start up, the first TextBox doesn't have focus!
you can do this by two method
just make the "TabStop" properties of desired textbox to false now it will not focus even if you have one text field
drag two text box
make one visible on which you don't want foucus which is textbox1
make the 2nd one invisible and go to properties of that text field and select
tabindex value to 0 of textbox2
and select the tabindex of your textbox1 to 1
now it will not focus on textbox1
If all you want is the optical effect that the textbox has no blue selection all over its contents, just select no text:
textBox_Log.SelectionStart = 0;
textBox_Log.SelectionLength = 0;
textBox_Log.Select();
After this, when adding content with .Text += "...", no blue selection will be shown.
Please try set TabStop to False for your view control which is not be focused.
For eg:
txtEmpID.TabStop = false;
You can try:
textBox1.Enable = false;
using System.Windows.Input
Keyboard.ClearFocus();
Kinda late to the party in 2022, however none of the solutions here worked for me (idk why) using .Net_6.0_windows, so I've come up with this solution:
Label focusoutLabel = new Label() {
Text = "",
Name = "somegenericplaceholdernamethatwillneverbeusedinmyprogram",
Visible = false,
};
this.Controls.Add(focusoutLabel);
this.ActiveControl = focusoutLabel;
^Place this code to your Form load handler^
In the constructor of the Form or UserControl holding the TextBox write
SetStyle(ControlStyles.Selectable, false);
After the InitializeComponent();
Source: https://stackoverflow.com/a/4811938/5750078
Example:
public partial class Main : UserControl
{
public Main()
{
InitializeComponent();
SetStyle(ControlStyles.Selectable, false);
}

Winforms c# - Set focus to first child control of TabPage

Say I have a Textbox nested within a TabControl.
When the form loads, I would like to focus on that Textbox (by default the focus is set to the TabControl).
Simply calling textbox1.focus() in the Load event of the form does not appear to work.
I have been able to focus it by doing the following:
private void frmMainLoad(object sender, EventArgs e)
{
foreach (TabPage tab in this.tabControl1.TabPages)
{
this.tabControl1.SelectedTab = tab;
}
}
My question is:
Is there a more elegant way to do this?
The following is the solution:
private void frmMainLoad(object sender, EventArgs e)
{
ActiveControl = textBox1;
}
The better question would however be why... I'm not entirely sure what the answer to that one is.
Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure.
Try putting it in the Form_Shown() event. Because it's in a container, putting in the Form_Load or even the Form() constructor won't work.
Try to use textbox1.Select() instead of textbox1.Focus(). This helped me few times.
You just need to add the Control.Select() for your control to this code. I have used this to set focus on controls during validation when there are errors.
private void ShowControlTab(Control ControlToShow)
{
if (!TabSelected)
{
if (ControlToShow.Parent != null)
{
if (ControlToShow.Parent.GetType() == typeof(TabPage))
{
TabPage Tab = (TabPage)ControlToShow.Parent;
if (WOTabs.TabPages.Contains(Tab))
{
WOTabs.SelectedTab = Tab;
TabSelected = true;
return;
}
}
ShowControlTab(ControlToShow.Parent);
}
}
}
I had a user control within another user control. textbox1.Select() worked for me but textbox1.Focus() did not work.
You can also try setting Tabstop to false, textbox1.Focus(), TabStop true.
private void ChildForm1_Load(object sender, EventArgs e)
{
ActiveControl = txt_fname;
}
i use this code it works fine on win tab control or dotnetbar supertab contrl

Categories

Resources