find control base on function in winform - c#

I have a function that is linked to a control. If I double click the control the editor will go to the function below.
My question is if I have function below and I know it is linked to a control, is there shortcut to find this control on the screen ?
In some situations there are to many controls and indicators on screen, it is difficult to search all the controls and indicator names in controls and indicator list.
private void MOVE_START_Click(object sender, EventArgs e)
{
}

(I assume you want to find the control in the designer, not at runtime).
You can easily find the control(s) that use this handler by right-clicking the MOVE_START_Click method and selecting "Find All References". It should show something like:
Form1.Designer.cs - (1, 1): button1.Click += new System.EventHandler(MOVE_START_Click);
Then in the designer, just above the properties window, you can select that control from the combobox:

No there is no short cut that gets automatically created.
One thing you could do is have the form with all of the controls on it listen for key down events. First you have to set the KeyPreview property on the form to true then add a KeyDown event listener to the form. After that you can listen for specific hot-keys to be pressed like ctrl-f
private void form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F && e.Modifiers == Keys.Control)
{
// Set the control you want to map to the hotkey as active here
myControl.Focus()
}
}

Related

C# WindowsForms - Hide control after clicking outside of it

C# WindowsForms - Hide control after clicking outside of it
I have a picturebox (f.e. picturebox1) which is not visible as default. When I click a button (let's say button1) the picturebox1 will show up. Now -> I need the picturebox1 to become hidden again when I click outside of it (on form itself or any other control). It works the same as a contextmenu would work.
I have no idea how to do it since any "Click_Outside" event doesn't exist. Is there any simple way to do this? Thanks.
Here is a simple solution, albeit not one that is totally easy to fully understand as it does involve catching the WndProc event and using a few constants from the Windows inderds..:
This is the obvious part:
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.Show();
}
Unfortunately we can't use the pictureBox1.LostFocus event to hide the Picturebox.
That is because only some controls can actually receive focus when clicking them; a Button or other interactive controls like a ListBox, a CheckBox etc can, too.
But a Panel, a PictureBox and also the Form itself can't receive focus this way. So we need a more global solution.
As ever so often the solution comes form the depths of the Windows message system:
const int WM_PARENTNOTIFY = 0x210;
const int WM_LBUTTONDOWN = 0x201;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN || (m.Msg == WM_PARENTNOTIFY &&
(int)m.WParam == WM_LBUTTONDOWN))
if (!pictureBox1.ClientRectangle.Contains(
pictureBox1.PointToClient(Cursor.Position)))
pictureBox1.Hide();
base.WndProc(ref m);
}
Note that we need to make sure that you can still clcik on the PictureBox itself; so we check if the mouse is inside its ClientRectangle..
Simply add this to the form code and every click outside the PictureBox will hide it.
Use the LostFocus event of the control (in your case, a PictureBox control)
As you said, the ClickOutside doesn't exist, so you have few choices:
Loop through all the controls of your form (Form.Controls) and add a click event that hides the PictureBox excluding your "Show" button.
You can intercept the mouse click message at the source like in this example: intercept
The easiest way is this:
Copy and paste the following method anywhere in your code:
private void mouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && pictureBox1.Visible == true)
pictureBox1.Visible = false;
}
then inside your form_Load Event copy and paste the following code:
foreach (Control ctrl in this.Controls)
if (ctrl is GroupBox || ctrl is .....)
ctrl.MouseClick += mouseClick;
of course you should repeat this loop for every groupBox within another groupBox and replace the dots with textbox, button, combobox, label, ... according to what controls you have

ToolsStripDropDownButton doesn't respond to PerformClick

I added a System.Windows.Forms.ToolStripDropDownButton in my Windows forms application and now I'm trying to add a keyboard shortcut for clicking this button
However, when I invoke button.PerformClick() it simply doesn't open:
void _Cnc_KeyPress(object sender, KeyPressEventArgs ){
btnFiltros.PerformClick();
}
Is this by design? Is there another way to simulate the click or properly open the dropdown?
Edit
The reason I'm doing this is I have a working application that is going to be used in a mouseless device, so I have to make the whole navigation possible from the keyboard
Does your form have the KeyPreview property set ? You need it to receive all key events.
When this property is set to true, the form will receive all KeyPress, KeyDown, and KeyUp events. After the form's event handlers have completed processing the keystroke, the keystroke is then assigned to the control with focus.
Form http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx
For the toolstripdropdownbutton you have to select the drop down item first. The following code snippet shows how to do that.
// This method shows the drop-down for the first item
// in the form's ToolStrip.
private void showButton_Click(object sender, EventArgs e)
{
ToolStripDropDownItem item = this.toolStrip1.Items[0] as ToolStripDropDownItem;
if (item.HasDropDownItems)
{
item.ShowDropDown();
}
}

Is there any way to detect a mouseclick outside a user control?

I'm creating a custom dropdown box, and I want to register when the mouse is clicked outside the dropdown box, in order to hide it. Is it possible to detect a click outside a control? or should I make some mechanism on the containing form and check for mouseclick when any dropdownbox is open?
So I finally understand that you only want it to close when the user clicks outside of it. In that case, the Leave event should work just fine... For some reason, I got the impression you wanted it to close whenever they moved the mouse outside of your custom dropdown. The Leave event is raised whenever your control loses the focus, and if the user clicks on something else, it will certainly lose focus as the thing they clicked on gains the focus.
The documentation also says that this event cascades up and down the control chain as necessary:
The Enter and Leave events are hierarchical and will cascade up and down the parent chain until the appropriate control is reached. For example, assume you have a Form with two GroupBox controls, and each GroupBox control has one TextBox control. When the caret is moved from one TextBox to the other, the Leave event is raised for the TextBox and GroupBox, and the Enter event is raised for the other GroupBox and TextBox.
Overriding your UserControl's OnLeave method is the best way to handle this:
protected override void OnLeave(EventArgs e)
{
// Call the base class
base.OnLeave(e);
// When this control loses the focus, close it
this.Hide();
}
And then for testing purposes, I created a form that shows the drop-down UserControl on command:
public partial class Form1 : Form
{
private UserControl1 customDropDown;
public Form1()
{
InitializeComponent();
// Create the user control
customDropDown = new UserControl1();
// Add it to the form's Controls collection
Controls.Add(customDropDown);
customDropDown.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
// Display the user control
customDropDown.Show();
customDropDown.BringToFront(); // display in front of other controls
customDropDown.Select(); // make sure it gets the focus
}
}
Everything works perfectly with the above code, except for one thing: if the user clicks on a blank area of the form, the UserControl doesn't close. Hmm, why not? Well, because the form itself doesn't want the focus. Only controls can get the focus, and we didn't click on a control. And because nothing else stole the focus, the Leave event never got raised, meaning that the UserControl didn't know it was supposed to close itself.
If you need the UserControl to close itself when the user clicks on a blank area in the form, you need some special case handling for that. Since you say that you're only concerned about clicks, you can just handle the Click event for the form, and set the focus to a different control:
protected override void OnClick(EventArgs e)
{
// Call the base class
base.OnClick(e);
// See if our custom drop-down is visible
if (customDropDown.Visible)
{
// Set the focus to a different control on the form,
// which will force the drop-down to close
this.SelectNextControl(customDropDown, true, true, true, true);
}
}
Yes, this last part feels like a hack. The better solution, as others have mentioned, is to use the SetCapture function to instruct Windows to capture the mouse over your UserControl's window. The control's Capture property provides an even simpler way to do the same thing.
Technically, you'll need to p/invoke SetCapture() in order to receive click events that happen outside of your control.
But in your case, handling the Leave event, as #Martin suggests, should be sufficient.
EDIT: While looking for an usage example for SetCapture(), I came across the Control.Capture property, of which I was not aware. Using that property means you won't have to p/invoke anything, which is always a good thing in my book.
So, you'll have to set Capture to true when showing the dropdown, then determine if the mouse pointer lies inside the control in your click event handler and, if it doesn't, set Capture to false and close the dropdown.
UPDATE:
You can also use the Control.Focused property to determine if the control has got or lost focus when using a keyboard or mouse instead of using the Capture with the same example provided in the MSDN Capture page.
Handle the Form's MouseDown event, or override the Form's OnMouseDown
method:
enter code here
And then:
protected override void OnMouseDown(MouseEventArgs e)
{
if (!theListBox.Bounds.Contains(e.Location))
{
theListBox.Visible = false;
}
}
The Contains method old System.Drawing.Rectangle can be used to indicate if
a point is contained inside a rectangle. The Bounds property of a Control is
the outer Rectangle defined by the edges of the Control. The Location
property of the MouseEventArgs is the Point relative to the Control which
received the MouseDown event. The Bounds property of a Control in a Form is
relative to the Form.
You are probably looking for the leave event:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx
Leave occurs when the input focus leaves the control.
I just wanted to share this. It is probably not a good way of doing it that way, but looks like it works for drop down panel that closes on fake "MouseLeave", I tried to hide it on Panel MouseLeave but it does not work because moving from panel to button leaves the panel because the button is not the panel itself. Probably there is better way of doing this but I am sharing this because I used about 7 hours figuring out how to get it to work. Thanks to #FTheGodfather
But it works only if the mouse moves on the form. If there is a panel this will not work.
private void click_to_show_Panel_button_MouseDown(object sender, MouseEventArgs e)
{
item_panel1.Visible = true; //Menu Panel
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (!item_panel1.Bounds.Contains(e.Location))
{
item_panel1.Visible = false; // Menu panel
}
}
I've done this myself, and this is how I did it.
When the drop down is opened, register a click event on the control's parent form:
this.Form.Click += new EventHandler(CloseDropDown);
But this only takes you half the way. You probably want your drop down to close also when the current window gets deactivated. The most reliable way of detecting this has for me been through a timer that checks which window is currently active:
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
and
var timer = new Timer();
timer.Interval = 100;
timer.Tick += (sender, args) =>
{
IntPtr f = GetForegroundWindow();
if (this.Form == null || f != this.Form.Handle)
{
CloseDropDown();
}
};
You should of course only let the timer run when the drop down is visible. Also, there's probably a few other events on the parent form you'd want to register when the drop down is opened:
this.Form.LocationChanged += new EventHandler(CloseDropDown);
this.Form.SizeChanged += new EventHandler(CloseDropDown);
Just don't forget to unregister all these events in the CloseDropDown method :)
EDIT:
I forgot, you should also register the Leave event on you control to see if another control gets activated/clicked:
this.Leave += new EventHandler(CloseDropDown);
I think I've got it now, this should cover all bases. Let me know if I'm missing something.
If you have Form, you can simply use Deactivate event just like this :
protected override void OnDeactivate(EventArgs e)
{
this.Dispose();
}

How can you create Alt shortcuts in a Windows Forms application?

I'd like to create keyboard shortcuts for some controls in my Windows Forms application.
Example:
Notice the underlined, F E V P B.
I have a label and a textbox control. I'd like to associate that Alt keyboard shortcut to the label and the textbox. So if someone presses Alt + B, focus is given to the associated textbox. Is there a way to create this association?
When the label receives focus from pressing its accelerator key (set using the &), it forwards the focus to the next control in the tab order, since labels are not editable. You need the textbox to be next control in the tab order.
To view and correct the tab order of your form, use the View + Tab Order command in the IDE. Using TabPages or other containers adds a level of nesting to the tab order (e.g., 1.1, 1.2 instead of just 1 and 2), but if the label and textbox are within the same container it shouldn't be too hard to set properly.
Type &File or &Edit and you will get underline. That will automatically bind underlined letters with Alt keyword for shortcut.
EDIT.
You question has modified so I'd like to keep up with my answer. You would like to catch some keys combination (Alt + F) and set a focus to the text box.
You may try this solution using KeyDown event of the main form.
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.F)
{
this.textBox1.Focus();
}
}
To achieve this, you have to additionally set KeyPreview property of the form to true.
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.W)
{
btnShowConstructionCdFun();
}
}

focus to text box

I created a form with a label, textbox and a button. In the form load event I called the focus() function for the textbox. But when I run my code the cursor is not coming to textbox. I need the cursor to go to text box as soon as the form is loaded. How to do it?
If you simply need to make sure a certain control gets focus when you first load a form, then change the TabOrder properties of all your controls (in the Designer) so that the control in question is '0', and the other elements are going up from there, '1', '2', etc.
If you need to dynamically select a different control when you show a form depending on some condition, then use the following code:
private void Form1_Load(object sender, EventArgs e) {
// You need to show the form otherwise setting focus does nothing
// (there are no controls to set focus to yet!)
this.Show()
if (someCondition == true)
control.Focus();
else
control2.Focus();
}
Handle the Shown event instead. This code should work.
private void Form1_Shown(object sender, EventArgs e)
{
textBox2.Focus();
}
Don't call Focus in the Load event. Call it in the Activate event. That would work
You can set the TabIndex property of textbox to 0 if you always want the focus on textbox when form loads. (This property is always eventually set in the form.designer.cs. And you won't have to write any extra code in your form.cs.)

Categories

Resources