C# WinForms showing a control as a dropdown - c#

Gretings
I need to have a custom control for my application. Basically its an expression editing GUI. You have, say, expression:
If variable_x is greater than variable_y
And you can click on "greater than" and change it to other comparator (like, equal to or less than).
The control thus must look like a label, but when you click it, it must show a dropdown (like combobox does) that has a listview inside (or maybe some other control) so that user can choose something. In a sense, i need a combobox without the box itself, replaced by something else (in this case, a label).
I know how to make custom controls, i understand i must somehow DropDown on mouse click or enter keypress, and hook events so that when whatever i dropped has closed, the choice is made, and also somehow track if user clicked elsewhere so i can close this dropdowned control. But i dont know if this is easy to do (some built-in method exists) or i have to do it all myself? Dont want to redevelop the wheel....
Please tell me if there are easy ways to do this.
Thanks!

You can extend the ComboBox control to update the DropDownStyle on Enter and LostFocus events.
public partial class MyComboBox : ComboBox
{
public MyComboBox()
{
InitializeComponent();
this.Dock = DockStyle.Fill;
this.SelectionChangeCommitted += this.OnComboBoxSelectionChangeCommitted;
this.Enter += this.OnControlEnter;
this.LostFocus += this.OnComboBoxLostFocus;
}
private void OnControlEnter(object sender, EventArgs e)
{
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
private void OnComboBoxLostFocus(object sender, EventArgs e)
{
this.DropDownStyle = ComboBoxStyle.Simple;
}
private void OnComboBoxSelectionChangeCommitted(object sender, EventArgs e)
{
// Notify to update other controls that depend on the combo box value
}
}

Related

Grabbing the textbox label

Hello im making my first project with about 10 different textboxes where the user puts data in. when he/she clicks the the textbox the textbox text clears and a virtual numpad form pops up and when he leaves the textbox the numpad "hides".
right now (or i would) i have 2 events for every textbox, a click event and a leave event,
private void sheetWidthBox_Enter(object sender, EventArgs e)
{
vnumPadForm.Location = PointToScreen(new Point(sheetWidthBox.Right, sheetWidthBox.Top));
vnumPadForm.Show();
}
Im sure there is a way of dynamically coding that in one event and just grabbing the label name. i have played around with it a bit on my numpad like this and it works good;
private void button_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
string num = b.Text;
SendKeys.SendWait(num);
}
Like that but instead i want to get the label name
right now (or i would) i have 2 events for every textbox, a click event and a leave event,
it works but very inefficient.
Change the name of the handler to something generic like "anyBox_Enter()", and update to the code below:
TextBox curTextBox = null;
private void anyBox_Enter(object sender, EventArgs e)
{
curTextBox = sender as TextBox;
vnumPadForm.Location = PointToScreen(new Point(curTextBox.Right, curTextBox.Top));
vnumPadForm.Show();
}
Note that I added a class level variable called "curTextBox" that gets set from the generic handler! This will track whatever TextBox was entered last.
Now, one by one, select each TextBox on your Form that you want to wire up to this common handler. After selecting each one, in the Properties Pane, click on the "Lightning Bolt" Icon to switch to the events for that control if they are not already showing. Find the "Enter" entry and change the dropdown to the right so that it says "anyBox_Enter".
Then in your button click handlers you can use the "curTextBox" variable to know where to send the key:
private void button_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
string num = b.Text;
if (curTextBox != null) {
curTextBox.Text = num; // or possibly APPEND this to the TB?
}
}

DevExpress select all when clicked on GridView cell (TextEdit)

I need to make it so when the user clicks on a cell with TextEdit in a grid view, it will select all in the textedit. I tried many many ways i could find in the internet, but none of them work well.
"EditorShowMode = MouseUp" way breaks everything, for example when you click on a cell that has checkedit; it selects the cell, then you need o click again to actually click on the CheckEdit.
"Use EditorShowMode = MouseUp and manually handle other things on MouseDown" is just ew. Won't work fine for all types of controls.
"Change selection length etc. on ShownEditor event" way doesn't work too, actually it selects the text when clicked, but it doesn't override the default function so the selection instantly changes. Also tried the SelectAll method but it had some problems that i dont remember (probably didnt work at all).
I have really tried many things, but couldn't find a totally fine way. Please tell me if you can get a working way without breaking other types of controls in the grid.
Answered by Pavel on DevExpress Support (works great):
The easiest way to achieve this is to use the GridView.ShownEditor event to subscribe to the active editor's MouseUp event. Then, select all text in the MouseUp event handler and detach this handler to avoid subsequent text selection.
private void GridView_ShownEditor(object sender, EventArgs e)
{
GridView view = sender as GridView;
if (view.ActiveEditor is TextEdit)
view.ActiveEditor.MouseUp += ActiveEditor_MouseUp;
}
private void ActiveEditor_MouseUp(object sender, MouseEventArgs e)
{
BaseEdit edit = sender as BaseEdit;
edit.MouseUp -= ActiveEditor_MouseUp;
edit.SelectAll();
}
You could use GridView CustomRowCellEdit event and set an event of text editor such as Mouse Up. Setting the RepositoryItemTextEdit MouseUp event can be set as in the example.
Example:
private void gridView1_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
{
if (e.RepositoryItem is DevExpress.XtraEditors.Repository.RepositoryItemTextEdit)
{
DevExpress.XtraEditors.Repository.RepositoryItemTextEdit rep = new DevExpress.XtraEditors.Repository.RepositoryItemTextEdit();
rep.ReadOnly = false;
rep.MouseUp += rep_MouseUp;
e.RepositoryItem = rep;
}
}
void rep_MouseUp(object sender, MouseEventArgs e)
{
DevExpress.XtraEditors.TextEdit te = sender as DevExpress.XtraEditors.TextEdit;
te.SelectAll();
}
You should handle Enter event for TextEdit
private void myRepositoryItemTextEdit_Enter(object sender, EventArgs e)
{
var editor = (DevExpress.XtraEditors.TextEdit)sender;
BeginInvoke(new MethodInvoker(() =>
{
editor.SelectionStart = 0;
editor.SelectionLength = editor.Text.Length;
}
}

Windows Forms click event not fired when clicking on label?

I have Windows Form TestForm, and in my Form I have several labels that are only used to display some text.
I need to display a MessageBox.Show anytime the Form is clicked. So I have an event handler for the click, which looks like this:
private void TestForm_Click(object sender, EventArgs e)
{
MessageBox.Show("The form has been clicked");
}
Unfortunately, the click event doesn't fire when I click over a label in the Form. Is there a way to fix this, besides consuming the click event for the labels?
Thanks.
To use the same click event for all labels:
In the properties for each label, go to the Events (lightning bolt tab).
You will see (probably near the top) a label for Click, click the dropdown for this event, and you will be shown a list of handlers that you could use for that label.
Here's the Properties > Events > Click handler (bottom right):
Because all of your labels are of the same type, and produce the same EventArgs, you are able to use the same handler for all of them.
Then, when you are adding more Labels, just choose the event handler from the Click event dropdown:
Hope this helps!
To flesh out LarsTech's comment, I have used something like this in the past when I was having problems with labels overlapping each other and lack of true transparency in WinForms. What I did was make the labels invisible on the Form, then iterate through them in the Form's paint event, pull the information out of them and then use Graphics.DrawString to draw the text. That way you you will still be able see them in design mode.
This is a quick example of what I mean.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
foreach (var temp in this.Controls)
{
if (temp is Label) //Verify that control is a label
{
Label lbl =(Label)temp;
e.Graphics.DrawString(lbl.Text, lbl.Font, new SolidBrush(lbl.ForeColor), new Rectangle(lbl.Location, lbl.Size));
}
}
}
private void Form1_Click(object sender, EventArgs e)
{
MessageBox.Show("The Form has been clicked");
}
}

Defocusing TextBox by clicking it again

I'm making a settings form, where user can assign custom hotkeys for the application. There's a TextBox, and by clicking it with mouse, it focuses and waits for one keypress and then defocuses (by focusing another label):
private void txtKey_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
}
private void txtKey_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.Text = e.KeyCode.ToString();
label1.Focus();
}
Is there a way to defocus focused TextBox (and cancel the key assinging process), by either clicking it again with mouse, or by clicking the GroupBox around it? I can't figure out how to check if TextBox was already focused when clicked (because when clicked, it gets focused before I can test if it's focused). Of course I can add a button "Cancel" next to the TextBox, but that's not what I want.
There is no Click-event for GroupBox, so I can't defocus TextBox by clicking GroupBox around it. Or can I somehow?
You can set/remove the Focus with
Keyboard.Focus = null;
You can also register to the following event:
public event MouseButtonEventHandler PreviewMouseLeftButtonDown
This event fires every time you click on the TextBox, thus you can set the Focus there if you want to.
For Winforms there is a way as well. I'm not proficient in it, but here would be a way:
Make a textBox (e.g. named textBoxFocus) that lies outside your window. Size it 1, 1 and move it to -10,-10 for example. Then you can register to the Click event and write
textBoxFocus.Focus();
It's a bit of a roundabout way, but should achieve what you want.
Thanks to private_meta for getting me to right direction (in comments)! I set the flag with click event, and before setting the flag, testing if flag is set. So first click does not find the flag, but second will. And flag is cleared within textbox Enter-event (which fires before Click-event). Now every other click focuses and every other defocuses textbox, as I wanted.
private void txtKey_Enter(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
textBox.Tag = null;
}
private void txtKey_Click(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Tag != null) label1.Focus();
textBox.Tag = "clicked";
}
One of the simple way is that, you may use a bool flag here.
Algorithm:
By default, the bool value is 0;
If(Textbox Selected && flag = 0)
Do your task; and flag = 1;
I hope I could satisfy your query and you can follow this algorithm.

How to handle Copy for multiple controls when adding a ShortcutKey to menu item?

If I do not create an "Edit->Copy" menu item and assign it the shortcut keys "CTRL+C", then I can select a control (RichTextBox, DataGridView, etc..) and hit "CTRL+C" and the control itself will handle the copy. I can copy text out, and paste it into notepad, etc..
Now throughout my whole form, I have a lot of controls. But I have a custom control that I want to make clear that I handle Copy functionality for. So I added the ShortcutKey CTRL+C to Edit->Copy, and by default it is set to Enabled.
Now, I have to implement an event handler for the 'click' event on that menu item. If I explicitly put in code to handle the copy, then it works:
public void menuEditCopy_Click(object sender, EventArgs e)
{
myCustomControl.Copy();
}
However, now Copy does not work on any other type of control. My first inclination was to find out the type of control that has focus, and implement a limited set of copy code for each of them:
public void menuEditCopy_Click(object sender, EventArgs e)
{
if (this.ActiveControl is MyCustomControl)
{
((MyCustomControl)this.ActiveControl).Copy();
}
else if (this.ActiveControl is RichTextBox)
{
((RichTextBox)this.ActiveControl).Copy();
}
}
etc...
However, my controls are added to a SplitContainer, and debugging shows that this.ActiveControl is set to the splitcontainer instance, not the control, even though I know that control is selected.
So my last thought is to literally check if every control has focus:
public void menuEditCopy_Click(object sender, EventArgs e)
{
if (myCustomControl.Focused)
{
myCustomControl.Copy();
}
else if (richTextBox1.Focused)
{
richTextBox1.Copy();
}
}
I would like to avoid this if possible, it is a lot of controls, and if I add a new control, I would need to update it. Is there a better way of doing this?
Thanks
A SplitContainer implements ContainerControl, so you could check for either one and look for it's ActiveControl instead. ContainerControl is the base class, so I would go for that - you might catch another type of container as well:
private void DoCopy(Control control)
{
if(control is ContainerControl)
DoCopy(control.SelectedControl);
else if(control is MyCustomControl)
((MyCustomControl)control).Copy();
else if(control is RichTextBox)
((RichTextBox)control).Copy();
else
throw new NotSupportedException("The selected control can't copy!");
}
void menuEditCopy_Click(object sender, EventArgs e)
{
DoCopy(this.ActiveControl);
}
You could try settting the KeyPreview property of your form to true. Then you could set up a handler for the form's KeyDown event which would look like the following:
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if(e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
{
if (ActiveControl.GetType() == typeof(MyCustomControl))
{
((MyCustomControl)ActiveControl).Copy();
e.Handled = true;
}
}
}
Here you are specifying that you have handled the Ctrl-C event by setting the event args Handled property to true. Else, if you leave it as false, the Ctrl-C key press will be handled as per usual by each individual control.
Because we have set the KeyPreview to true the form's handler gets to see each key press before any other control that it contains and can decide to deal with the key press itself or else allow it to be handled in the same way as if the form had never previewed it.
I think as well it would be necessary to remove the short-cut key from your menu item (although you could still manually put the text "Ctrl+C" next to your menu item name) for this to work, otherwise your menu item will hijack the key stroke.

Categories