How can I make my Form visible/invisible by pressing insert? - c#

I'm trying to find out how to making my form invisible when I press insert and when I press insert again it makes the form visible. I try to find out how, but no one seems to have what I am looking for.

A simple example how you can manipulate Form's visibility by handling the Insert key down:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// Don't forget to enable Form.KeyPreview in order to receive key down events
if (e.KeyCode == Keys.Insert)
{
Visible = false;
}
}
}
You can set Visible back to true to make it visible. However, you will not be able to do this, because Form became invisible and doesn't receive key down events anymore. In this case you can try to set the global hotkey using, for example, the GlobalHotKey library described here. Note also, that it doesn't make sense to set a single key (e.g. Insert) as global hotkey as in most cases system or another application will capture it.

You can do this:
private void InfoForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert) Opacity = Opacity == 0 ? 1 : 0;
}
For this to work you need to turn on the Form's KeyPreview property!
But turning visiblity back on (or to be precise turning off opacity) will only work if no other program has received focus in the meantime.
If that might happen you need to set a global keyboard hook; make sure to pass the Insert key back on or else many other programms will no longer work right.. All in all I would not recommend it..
I'm not sure when the whole idea might make sense. One answer could be to show or hide a popup data window that is only meant to show some additional information popping up from a base data window.
In that case you could simply close the window whenever it gets deactivated:
private void InfoForm_Deactivate(object sender, EventArgs e)
{
this.Close();
}

Related

How to switch to a next "Entity" (Example TB or MaskedTB) on the form with a specific key press

I am trying to find a solution to replicate what tab does when you are focused on a specific TextBox or MaskedTextBox, I already set my TabIndexs in order through Properties in VS
FormaNalaza is a form
private void FormaNalaza_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Switch to the next TabIndex Entity
}
}
This was my solution but I couldn't figure out how to change the focus to the next Entity in the form
I tried SelectNextControl(*The starting Entity*, 1, 0, 0, 0)
EDIT
Form Events
DateTimePicker Events (Its the first DataBox in the form...)
Code (2nd one works when it focused on the DTP)
IDK why but I am guessing it could be because from the start of the form there is a focus on a TB instead of the form but still that explanation is so stupid but if it works ill use it. It will take me 20min to generate methods and call a function that executes the code you provided...
keep in mind this is .NET Framework and as far as i know, it's old. I am guessing that you are using .NET Core
Simple Implementation:
private void FormaNalaza_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Switch to the next TabIndex Entity
SendKeys.Send("{Tab}");
}
}
Tab Order
Output:
Add it to the event:
The tab key does this automatically, so if you are ok with pressing tab instead of enter, you can do that. Changing the TabIndex property of your entities will change the order in which tab will switch between them.

How to tell if a ChildWindow is the 'top most' window

I'm working in Silverlight, but potentially a WPF solution would work as well.
My problem is very simple. I have lots of modal Child Windows that can be open, and in their generic menu is a home button. This button is supposed to close all of the child windows and return to the base screen. I have a few different types of 'generic child windows' that host lots of different UserControls, so by far the easiest way to implement this is to, when the window comes into focus, check if the global ReturnToHome bool is true, and if it is, just close it.
I've tried all of these
private void ChildWindow_GotFocus(object sender, RoutedEventArgs e)
{
if (CommonResources.ReturnToHome) DialogResult = false;
}
private void ChildWindow_MouseEnter(object sender, MouseEventArgs e)
{
if (CommonResources.ReturnToHome) DialogResult = false;
}
private void ChildWindow_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (CommonResources.ReturnToHome) DialogResult = false;
}
The issue is, GotFocus doesn't fire until I actually click on the window. MouseEnter is a little better, but doesn't fire until I move the mouse. IsEnabledChanged never fires because the Child Window doesn't disable anything. Checking every child window when it closes to see if Home has been clicked isn't easy because of the sheer number of places where you can open child windows, and several of them are nested within User Controls where I couldn't even easily access DialogResult. Any idea how I could do this?
Also I should note that I want each of the windows to close one by one, from top down, because each window that closes does its own verification to see if it should warn the user before closing (giving the user the option to cancel closing)
TopMost is a bool property which is either set to true or false and as far as I'm aware, there is no public property like Z-Index that will tell you the order in which your Windows were set to TopMost. However, there is a simple solution... just maintain a static int variable that will register this order. Each time you add a new Window, set the number into its Tag property:
Window childWindow = new Window();
childWindow.Tag = currentWindowNumber++;
...
childWindow.ShowDialog();
Then, when you want to close them in order, you can just do something like this:
foreach (Window window in Application.Current.Windows.OfType<YourWindowType>()
.OrderBy(w => (int)w.Tag))
{
((AnimationWindow)window).CloseWindow();
}

Focus picturebox when entering form

I am creating a simple game for school in C#, where I am controlling a character using the WASD keys. The character is taken from a sprite sheet and put into an imagelist. The imagelist is in a picturebox.
Everything works fine when it's just the picturebox in the form, but when I add a button or something else, it's like it lose focus. It doesn't respond.
I have searched endless pages for a solution to set focus on the picturebox when the form opens, but I haven't found anything that works.
I would really appreciate some help.
Edit: It's WinForms.
The PictureBox cannot take the focus. It is intended as a way to show an image but not intended to allow user input such as via the keyboard.
A crude approach would be to intercept the OnKeyDown event on the Form itself and then test for the keys of interest. This will work as long as the control that has the focus, such as your Button, does not want to process those keys itself.
A better approach would be to override ProcessCmdKey() method of the Form. This method is called on the target control, such as your Button, to decide if the key is special. If the Button does not recognize it as special then it calls the parent control. In this way your Form level method will be called for each key press that is not a special key for the actual target. This allows the Button to still process a ENTER key which is used to press the Button but other keys will be processed by your Form.
Lastly, to intercept all keys before they are handled by any of the controls on the Form you would need to implement the IMessageFilter interface. Something like this...
public partial class MyWindow : Form, IMessageFilter
{
public MyWindow()
{
InitializeComponent();
Application.AddMessageFilter(this);
}
public bool PreFilterMessage(ref Message m)
{
// WM_KEYDOWN
if (m.Msg == 0x0100)
{
// Extract the keys being pressed
Keys keys = ((Keys)((int)m.WParam.ToInt64()));
// Test for the A key....
if (keys == Keys.A)
{
return true; // Prevent message reaching destination
}
}
}
return false;
}
I found event MouseHover with pictureBox1_Hover calling pictureBox1.Focus() worked. When the mouse was hovered over the PictureBox in question, it would gain focus. Other than that, it didn't seem that calling pictureBox1.Focus() during form load had any effect on the focus.
this.pictureBox1.MouseHover += new System.EventHandler(this.pictureBox1_Hover);
private void pictureBox1_Hover(object sender, EventArgs e)
{
pictureBox1.Focus();
}
It worked for me!

Navigation in Windows Forms using enter key

I have textboxes in my Windows Forms application, and I want that when the user presses the ENTER key then the cursor goes to the next textbox.
How do I do this?
Is this a good habit or shall I avoid it? Actually the users are very much prone and have adapted and have become habitual of pressing ENTER key for navigation between textboxes and buttons. So, for them I need to do this.
Please help me with the complete code using two text-boxes as an example.
I would say the nicest way is to create a user control that inherits from TextBox and then override the OnKeyPress method to capture enter and send a tab. Focus will then be given to the next TabIndex on the form, just as though a tab had actually been entered.
The code below does exactly that:
public partial class CustomTextbox : TextBox
{
public CustomTextbox()
{
InitializeComponent();
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
e.Handled = true;
SendKeys.Send("{TAB}");
}
}
}
You could also put similar code in the KeyPress event handlers for your controls but this saves a lot of duplicate code and unnececessary event handler.
As for whether this is good practice - I would say in general, no, changing the default behaviour of forms is never a good idea, but of course, if this is what your users want and expect, then it is their decision.
This is a bad idea. The standard UI is for TAB to move between input fields. You make your app less useable when you elect not to follow well known standards. These standards are what makes UI intuitive.
Yes, it depends on you
For a sample, you can place 4 textbox on the form and use the following code
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.Focus();
}
}
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox3.Focus();
}
}
private void textBox3_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox4.Focus();
}
}
It might help you.
Happy coding...
For example you could trap OnKeyUp event, check if it is RETURN and process source control to use Focus() to next control...
Yes you can fire the KeyDown or KeyUp event on a TextBox. To check whether it was the enter key, you can do the following:
//e is the KeyEventArgs from the event.
e.KeyCode == Keys.Enter
Then, if he has pressed the enter key, you can do:
System.Windows.Forms.Control.SelectNextControl();
To set the order of your controls, in Visual Studio look for this little icon:
http://i.stack.imgur.com/nZWLO.png
Click it, and you'll go into tab ordering mode, as I like to call it. Just click the controls in the order you wish them to be and after you're done, click the little icon again. Presto!
Now whether that is a good idea of not, completely depends on how used to it your end users are. If they have always used it like this, and you give them something that doesn't fit into their mind model, they are going to say your software is broken.
Always always always try to emulate what processes the user already has in place in their head.
Read this if you have the time, it's a really light and very good read:
http://www.joelonsoftware.com/uibook/fog0000000249.html
I think the best way would be to:
1) assign each textbox's TabIndex attribute incrementally (first is x, next is x+1 etc).
2) capture on the OnKeyUp event on the whole form, check the argument to see if the key was RETURN
3) focus the next textbox using its TabIndex. Or simulate the TAB key.
This code should work:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
GetNextControl((TextBox)sender, true);
}
}
This way you end up writing only one function, and you can have as many textboxes as you want.

How to stop textbox leave event firing on form close

using c# winforms vs2008
I've got a textbox on a form with a method being called from the textBox1_Leave event. The method takes the contents of the textbox in question and populates other textboxes based on the contents.
My problem is that is the user has focus on the text box then clicks the button to close the form (calling this.close) then the form does not close because the textbox leave event gets fired.
If the textbox does not have focus on form close then the form closes fine.
If however a user closes the form by clicking the little X close icon in the top corner the it closes fine all the time with out the textbox leave event being fired.
How can I duplicate the X close functionality so that I can always close the form without the textbox leave event being fired?
The simplest solution is going to be to check which control is actually focused before doing your post-processing - but you can't do it in the Leave handler, because the focus will still be on the text box at that point.
Instead, you need to move your logic to the LostFocus event, which is not in the designer. You'll have to wire it up at runtime:
public class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.LostFocus += new EventHandler(textBox1_LostFocus);
}
private void textBox1_LostFocus(object sender, EventArgs e)
{
if (closeButton.Focused)
return;
// Update the other text boxes here
}
}
The LostFocus event happens to fire after the new control receives focus.
Clarification - you might find that it works by putting this logic in the Leave event - if the focus is changed by the mouse. If the keyboard is used instead, you'll get the wrong behaviour. LostFocus is reliable in both cases - the focused control will always be the "new" control. This is documented on MSDN: Order of Events in Windows Forms.
Incidentally, the reason why you're not having this problem with the "red X" is that the X is not actually a control that can receive focus, it's part of the window. When the user clicks that, it's not causing the text box to lose focus, and therefore isn't causing the Leave event to fire.
Another approach:
Use the textbox's validating event instead of it's leave event, then change the button's CausesValidation property to false. You will also have to set the textbox to not cause validation in the button's click event so the validating event will not fire when the form is closing (thanks to #Powerlord for pointing this out).
private void button1_Click(object sender, EventArgs e)
{
this.textBox1.CausesValidation = false;
this.Close();
}
You could also handle the FormClosing event and make sure the e.Cancel argument does not get set to true by the validating events on the other controls on the form. I think they will be fired off before the FormClosing event.
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = false;
return;
}
}
you can check to see which control has just got focus.
private void textBox1_Leave(object sender, EventArgs e)
{
if (btnClose.Focused)
return;
// go from here
}
Just check if the form owning the textbox is disposing? If it's getting closed, it's disposing. If it's disposing you could simply end the pesky 'leave' event without doing anything. I didn't check it and forgive me, I'm choked on a project of my own so and I was searching myself, so I don't think I'll have time for that.
private void GuiltyTextBox_Leave(object sender, EventArgs e) {
Form formOwningTheTextBox=(Form)((Control)sender).TopLevelControl;
if (formOwningTheTextBox.Disposing || formOwningTheTextBox.IsDisposed) return;
.......
}
I just believe this is going to work with minimum effort and wanted to send a quick answer before I resume searching my own answer.
Write Following line of code in text box leave event on top
if me.closing then
return
end if

Categories