Resize on the key firing - c#

I have a classic Form1 class that inherits the Form class.
The problem is I press the buttons and no events get fired.
Inside the Form1 there is a webBrowser which occupies the whole Form1.
Here is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
KeyPreview = true;
PreviewKeyDown += wb_PreviewKeyDown;
}
private void wb_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
Console.WriteLine("EDOOOOOOOOO");
if (e.Control && e.KeyCode == Keys.C)
{
// Do something funny!
}
}
}
The wb_PreviewKeyDown is not fired whatever button I push.

If you press a key on the form, the event will get fired.
However, if you have a TextBox or something on the form, and you press a key on that, the event will NOT fire, because now the TextBox has received the input.
This can easily be fixed by setting the property KeyPreview = true on the form.
You can set this in the designer, or in code (see the answer of #Isma)
EDIT:
Since you have a WebBrowser control on your form, you need to do it somewhat different, see this Handling key events on WebBrowser control
It involves using the PreviewKeyDown event of the WebBrowser

Related

Keypress event for dynamically created winform in C#

I'm creating a windows form at run-time. Now i want the Key-press event to be triggered for the dynamically created form.
How do i create/bind the event to newly/dynamically created windows form in C#.
Thanks,
If we take a text box its like this.
private void Form1_Load(object sender, EventArgs e)
{
TextBox myTextBox = new TextBox();
myTextBox.KeyPress += new KeyPressEventHandler(myTextBox_KeyPress);
this.Controls.Add(myTextBox);
}
void myTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
//Do Key press event work here
}
UPDATE
Make sure that the focus should be on Form2.
Try This.
Form dynamicForm = new Form();
dynamicForm.KeyPress += new KeyEventHandler(onkeyPress);
void onkeyPress(object sender, KeyEventArgs e)
{
Console.WriteLine("test");
}
Make sure the forms KeyPreview Property is set to true, that way it will see the keystrokes.
From above link:
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. For example, if the KeyPreview property is set to true and the currently selected control is a TextBox, after the keystroke is handled by the event handlers of the form the TextBox control will receive the key that was pressed. To handle keyboard events only at the form level and not allow controls to receive keyboard events, set the KeyPressEventArgs.Handled property in your form's KeyPress event handler to true.
So you will want to do something like this:
public partial class Form1 : Form
{
Form2 f2;
public Form1()
{
InitializeComponent();
KeyPreview = true;
KeyDown += Form1_KeyDown;
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.Control)
{
switch(e.KeyCode)
{
case Keys.C:
MessageBox.Show("Cntrl C");
break;
case Keys.V:
MessageBox.Show("Cntrl V");
break;
default:
break;
}
}
}
}

C# form Activated and Deactivate events

I have two forms, mainForm and subForm. When mainForm loses focus I want subForm to disappear and then reappear as mainForm regains focus. I'm using the Activated and Deactivate events on the mainForm to keep track of whether mainForm has focus or not. When the Activated is fired I do subForm.Show() and the opposite for Deactivate. The problem I have is that when subForm gains focus mainForm disappear because I don't know how to say programmatically "make subForm disappear when the mainForm's Deactivate event fires except if it's because the subForm gained focus. The whole point of what I'm doing is to make both windows disappear when the mainForm loses focus because the user clicked on another application or use ALT+TAB to switch. I don't want to leave the subForm behind. Is there any way of checking as the Deactive fires whether it was because another form belonging to the application gained focus as opposed to some other application?
class MainForm : Form
{
SubForm subForm = new SubForm();
private void mainForm_Activated(object sender, EventArgs e)
{
this.subForm.Show();
}
private void mainForm_Deactivate(object sender, EventArgs e)
{
this.subForm.Hide()
// I need some logic to make sure that it is only hidden
// when the mainForm loses focus because the user clicked
// some other application in the taskbar and not when the
// subForm itself gains the focus.
}
}
This works on my machine.
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private Form2 _form2;
private void Form1_Load(object sender, EventArgs e) {
_form2 = new Form2();
_form2.Show();
HandleFocusEvents();
}
private void HandleFocusEvents() {
this.LostFocus += Form_LostFocus;
_form2.LostFocus += Form_LostFocus;
this.GotFocus += Form_GotFocus;
}
private void Form_LostFocus(object sender, EventArgs e) {
if (!_form2.ContainsFocus && !this.ContainsFocus) {
_form2.Hide();
}
}
private void Form_GotFocus(object sender, EventArgs e) {
if (!_form2.Visible) {
_form2.Show();
}
}
}
In your main forms code, where you create an new instance of the sub form, add an event that is fired whenever the instance of the sub form form is activated. In the event handler for it set a bool variable to true. Now, do the same, for the deactivate event of the sub forms instance, except set the bool variable to false.
Now in the event for the main form loosing focus, before hiding it check that bool variable and make sure it is false "the sub form doesn't have focus" and only then would you hide the main form.
I could provide code if I could see what you have so far. There are a lot of different ways you could to this.
Hope this helps you!
If I understand it correctly, this sounds like just a normal MDI application. Can you make your main form the MDI Parent and set the sub form MDI parent to the main form? Most of these activation stuff that you are talking about should then be look after automatically? Or at most just trap the minimize event in the subform to then also minimize mdi parent form

Validating event not fired for child controls of picturebox

Yesterday I have implemented some validating events for controls in a groupbox located on a WinForm. I have set the AutoValidate property of the form to Disabled, I have set the CausesValidation property of the controls to true and implemented the Validating event of the controls. By calling the ValidateChildren() method of the form I force that validating events are executed. This was working all fine.
But after placing this groupbox on top of a picturebox and setting the picturebox as parent of the groupbox then validating events aren't executed anymore....
Below some demo code. Form is only containing a picturebox, groupbox, textbox and button.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_Validating(object sender, CancelEventArgs e)
{
MessageBox.Show("Validating textbox");
e.Cancel = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (ValidateChildren())
MessageBox.Show("Validation not executed :-(");
else
MessageBox.Show("Validation executed :-)");
}
private void Form1_Load(object sender, EventArgs e)
{
groupBox1.Parent = pictureBox1;
}
}
The ValidateChildren() method calls ValidateChildren(ValidationConstraints.Selectable) to get the job done. That's a problem for a PictureBox, it isn't selectable. So none of its children get validated either.
Calling it with ValidationConstraints.None doesn't work either, the ability to validate child controls is implemented by ContainerControl and PictureBox doesn't derive from it. So you can't call ValidateChildren on the PictureBox either. Enumerating the controls yourself and triggering the Validating event can't work either, the PerformControlValidation() method is internal.
You'll need to re-think the idea of trying to turn the PictureBox into a ContainerControl. Most any control can resemble a picturebox, if not through the BackgroundImage property then through the Paint event.

Prevent ShowDialog() from returning when OK button is clicked

I have a dialog that I want to prevent from closing when the OK button is clicked, but it returns, and that even if the AcceptButton property is set to none instead of my OK button. What is the best way to stop it from closing?
In fact you are changing the wrong property. You certainly do want AcceptButton to be the OK button. This property determines which is the default button in Windows terms. That is the button which is pressed when you hit ENTER on your keyboard. By changing AcceptButton you are simply breaking the keyboard interface to your dialog. You are not influencing in any way what happens when the button is pressed.
What you need to do is set the DialogResult property of your button to DialogResult.None since that's what determines whether or not a button press closes the form. Then, inside the button's click handler you need to decide how to respond to the button press. I expect that, if the validation of the dialog is successful, you should close the dialog by setting the form's DialogResult property. For example
private void OKbuttonClick(object sender, EventArgs e)
{
if (this.CanClose())
this.DialogResult = DialogResult.OK;
}
The best way to stop this behavior is changing the DialogResult property of your OK button to DialogResult.None in the property window at design time.
Also, If you have already some code in the click event of the OK button you could change the form DialogResult.
private void comOK_Click(object sender, EventArgs e)
{
// your code .....
// Usually this kind of processing is the consequence of some validation check that failed
// so probably you want something like this
if(MyValidationCheck() == false)
{
// show a message to the user and then stop the form closing with
this.DialogResult = DialogResult.None;
}
}
You need to remove the DialogResult of the button itself as well, in the properties window on the button set it to None.
http://msdn.microsoft.com/en-us/library/system.windows.forms.button.dialogresult.aspx
If the DialogResult for this property is set to anything other than
None, and if the parent form was displayed through the ShowDialog
method, clicking the button closes the parent form without your having
to hook up any events.
Obviously, now your button won't do anything so you will need to register a handler for the Click event.
The best practice is to actually set the Ok button to be disabled rather than not respond to user input.
The DialogResult property SHOULD be set to Ok or Yes depending on the form and the AcceptButton should also be linked to Ok.
I normally create a function on all dialogs and call it whenever the user interacts with the data.
void RefreshControls()
{
button.Enabled = this.ValidateInput();
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form2 fLogin = new Form2();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new Form1());
}
else
{
Application.Exit();
}
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnKlik_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}

C# - How to trigger opacity event when form loses focus?

Purpose is to have the opacity event trigger when the form loses focus. The form has a setting for STAY ON TOP. The visual effect would be to click on a possibly overlapping window, and yet the form when not focused on would stay on top, but in the corner slightly transparent, keeping it within easy access, but providing visibility to the stuff underneath.
I 've googled and googled, and can't figure out how to get this event to properly fire when form loses focus, and then when form gains focus back to restore opacity to 100% or the level determined elsewhere.
Tips?
// under designer.cs
//
// CollectionToolForm
//
//other code....
this.LostFocus += new System.EventHandler(goTransparent);
//method
private void goTransparent(object sender, EventArgs e)
{
if (transparentCheck.Checked == true)
{
this.Opacity = 0.50;
}
else
{
this.Opacity = 1;
}
}
It sounds as if you are looking for the Activated and Deactivate events.
Update
In response to the comment about LostFocus event, it could be of interest to clarify how it works. The LostFocus event of the Form is inherited from Control. It is raised when a controls loses focus; either because the form as such is being deactivated (focus moves to another application for instance), or because focus moves to another control within the same form.
If you hook up an event handler for the LostFocus event of a form that contains only at least one control that can receive focus, you will find that the LostFocus event of the form is raised immediately after the form is displayed. This is because focus moves from the form (which is a Control) to the first focusable control on the form.
So, the form being active and the form being focused are two separate behaviours.
You tried doing it with mouse enter/leave events?
public Form1()
{
this.MouseEnter += new System.EventHandler(this.Form1_MouseEnter);
this.MouseLeave += new System.EventHandler(this.Form1_MouseLeave);
}
private void Form1_MouseLeave(object sender, EventArgs e)
{
this.Opacity = 0.5;
}
private void Form1_MouseEnter(object sender, EventArgs e)
{
this.Opacity = 1;
}

Categories

Resources