How to force the form focus? - c#

How can I force the focus of an form? .Focus() is not working for me.
private void button1_Click(object sender, EventArgs e) {
var form = new loginForm();
if (Application.OpenForms[form.Name] == null) {
form.Show();
} else {
form.Focus();
}
}
What am I doing wrong?

You need to show the form first - use the Show() method:
var form = new loginForm();
form.Show();
Edit: (updated question)
For an existing form calling Activate() might be more appropriate, this also brings the form to the front:
private void button1_Click(object sender, EventArgs e)
{
var form = new loginForm();
if (Application.OpenForms[form.Name] == null)
{
form.Show();
}
else
{
Application.OpenForms[form.Name].Activate();
}
}
If the form is minimized you need to subscribe to the Activated event to change your window state to FormWindowState.Normal:
private void loginForm_Activated(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
}

Try this:
this.BringToFront();
this.Activate();

it should be
private void button1_Click(object sender, EventArgs e) {
var form = new loginForm();
if (Application.OpenForms[form.Name] == null) {
form.Show();
} else {
Application.OpenForms[form.Name].Focus();
}
}

None of the previous answers worked for me, but this does:
protected override void OnShown(EventArgs e)
{
Focus();
}
None of the focusing methods worked if called before this event. Hope it helps.

On start of the form we add
this.BringToFront();
this.Activate();

Related

Hide form when minimize doesn't work in Visual C#

I'm lookin for examples how hide form when I minimize, but this.Hide() doesn't work. I don't understand what's wrong. At the moment I just want to hide Form1.
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
this.Hide();
}
}
When I click in minimize button, form goes to taskbar but form doesn't hide.
I found a solution. After InitializeComponent():
public Form1()
{
InitializeComponent();
this.Resize += SetMinimizeState;
}
Then:
private void SetMinimizeState(object sender, EventArgs e)
{
bool isMinimized = this.WindowState == FormWindowState.Minimized;
this.ShowInTaskbar = !isMinimized;
if (isMinimized)
{
// optional
notifyIcon1.ShowBalloonTip(500, "Title", "Message.", ToolTipIcon.Info);
}
}
It works!

New form fails to appear

Can someone explain why my new form doesn't appear? The old form closes but it isn't replaced by my new one:
namespace Pong
{
public partial class Menu : Form
{
public Menu()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void PlayButton_Click(object sender, EventArgs e)
{
PongForm form = new PongForm();
form.Show();
this.Close();
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Is "Menu" the startup form for your application? If yes, then when it closes the entire application closes.
One solution would be to hide the current form, display "form" with ShowDialog(), then call Close():
private void PlayButton_Click(object sender, EventArgs e)
{
this.Visible = false; // hide the current form
Application.DoEvents();
PongForm form = new PongForm();
form.ShowDialog(); // code stops here until PongForm is dismissed
this.Close(); // now close the form (and presumable the whole app)
}

Close Parent with Modal Form

private void btnOpenModalWindow_Click(object sender, EventArgs e)
{
using (var modalForm = new modalForm(EventDetails))
{
modalForm.ShowDialog(this);
}
}
Inside the modal window:
private void btnOk_Click(object sender, EventArgs e)
{
Close();
}
I want to close the parent form also when I close the modal window but I'm not sure how to do that from the modal window.
Just call the Owner that you already passed as parameter to ShowDialog
private void btnOk_Click(object sender, EventArgs e)
{
this.Owner.Close();
}
Actually, a cleaner way is to do:
private void btnOpenModalWindow_Click(object sender, EventArgs e)
{
using (var modalForm = new modalForm(EventDetails))
{
if (modalForm.ShowDialog() == DialogResult.OK)
{
this.Close();
}
}
}
Allows you to check the return code if you don't want to exit. Or just close after ShowDialog.
Found exactly what I was looking for, and its so ridiculously simple I'm ashamed to have even asked.
Application.Exit();

ShowDialog with Parent still enabled

In one of our apps we want to want to limit the user from opening other menu items when an existing menu item is already open. We are currently doing this:
private void menuItem1_Click(object sender, EventArgs e)
{
Myform f = new MyForm();
f.ShowDialog(this);
}
However in doing this, we lose the ability to interact at all with the parent window because internally, the parent.enabled property was set to false. Using the code above, if the user has menu item open and wants to move the parent window to see something on their desktop, they first must close the menu item, move the parent, and reopen the menu item.
I have come up with the follow method of doing the UI in a backgroundworker
public class BaseForm : Form
{
private bool _HasChildOpen;
protected BackgroundWorker bgThead;
public BaseForm()
{
_HasChildOpen = false;
bgThead = new BackgroundWorker();
bgThead.DoWork += new DoWorkEventHandler(OpenChildWindow);
bgThead.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.ClearChildWindows);
}
protected void ClearChildWindows(object sender, RunWorkerCompletedEventArgs e)
{
_HasChildOpen = false;
}
public void OpenChildWindow(object sender, DoWorkEventArgs e)
{
if (!_HasChildOpen)
{
Form f = (Form)e.Argument;
f.StartPosition = FormStartPosition.CenterScreen;
f.ShowDialog();
}
}
}
and then each menu item has the following code
private void menuItem1_Click(object sender, EventArgs e)
{
if (!bgThead.IsBusy)
{
bgThead.RunWorkerAsync(new Myform());
}
}
but this approach is a big no no. However, using invoke seems to get me back where I started:
private void doUIWork(MethodInvoker d)
{
if (this.InvokeRequired)
{
this.Invoke(d);
}
else
{
d();
}
}
public void OpenChildWindow(object sender, DoWorkEventArgs e)
{
if (!_HasChildOpen)
{
doUIWork(delegate() {
Form f = (Form)e.Argument;
f.StartPosition = FormStartPosition.CenterScreen;
f.ShowDialog();
});
//Form f = (Form)e.Argument;
//f.StartPosition = FormStartPosition.CenterScreen;
//f.ShowDialog();
}
}
How do I properly limit the user to just one menu item open, but at the same time leave the parent enabled such that it can be moved resized etc?
You will need to programmatically disable menu strip behavior once one of the forms is open. So if you have Form1 and Form2, (with a menuStrip on Form1 and toolStripMenuItem1, toolStripMenuItem2 on the menuStrip):
private void menuItem1_Click(object sender, EventArgs e)
{
var f2 = new Form2();
f2.FormClosing += f2_FormClosing;
f2.Show();
this.menuStrip1.Enabled = false;
}
private void menuItem2_Click(object sender, EventArgs e)
{
var f2 = new Form2();
f2.FormClosing += f2_FormClosing;
f2.Show();
this.menuStrip1.Enabled = false;
}
void f2_FormClosing(object sender, FormClosingEventArgs e)
{
this.menuStrip1.Enabled = true;
}
using the Show() method instead of ShowDialog() enables interaction with the parent control, though you will need to manually disable/enable behavior depending on when the child control is shown or not.

Closing event handlers C#

I have two forms, Form 2 is inheriting from Form 1.
What I need to do is that when I close both Form 1 and Form 2 another form which asks if user is sure to quit appears. Then if user clicks Yes, another form which asks if the user wants to save the game appears if and only if the form which the user closes is Form 2 and not Form 1 since for Form 1 there is no saving necessary.
This is what I managed to do:
// These are the Form 1 closing and closed event handlers:
private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
SureClose sc = new SureClose();
sc.StartPosition = FormStartPosition.CenterScreen;
sc.Show();
}
private void GameForm_FormClosed(object sender, FormClosedEventArgs e)
{
MainMenu menu = new MainMenu();
menu.Show();
}
Then in Sure Close: // Please note that Tournament is Form 2 inheriting from GameForm (Form 1)
private void yesButton_Click(object sender, EventArgs e)
{
this.Hide();
if (GameForm.ActiveForm is Tournament)
{
SaveGame sg = new SaveGame();
sg.StartPosition = FormStartPosition.CenterScreen;
sg.Show();
}
else
{
GameForm.ActiveForm.Close();
}
}
private void noButton_Click(object sender, EventArgs e)
{
this.Hide();
}
// This is the SaveGame Form:
private void saveButton_Click(object sender, EventArgs e)
{
// Still to do saving!
}
private void dontSaveButton_Click(object sender, EventArgs e)
{
this.Hide();
GameForm.ActiveForm.Close();
}
The problem is that when in the yesButton event handler in SureClose Form I have GameForm.ActiveForm.Close(), this is going back to the GameForm Closing event handler therefore the SureClose dialog is appearing again.
I tried doing: if (e.CloseReason() == CloseReason.UserClosing)
but obviously it doesn't work either because the reason of closing will always be the user :/
How can I solve this?
Thanks a lot for any help !
Form1 :
private void GameForm_FormClosing(object sender, FormClosingEventArgs e)
{
if(SureClose())
{
SaveChanges();
}
else
{
e.Cancel = true;
}
}
private bool SureClose()
{
using(SureClose sc = new SureClose())
{
sc.StartPosition = FormStartPosition.CenterScreen;
DialogResult result = sc.ShowDialog();
if(result == DialogResult.OK)
{
return true;
}
else
{
return false;
}
}
}
protected virtual void SaveChanges()
{
}
Form2:
protected override void SaveChanges()
{
using(SaveGame sg = new SaveGame())
{
sg.StartPosition = FormStartPosition.CenterScreen;
DialogResult result = sg.ShowDialog();
if(result == DialogResult.OK)
{
//saving code here
}
}
}
SureClose form and SaveGame form:
private void yesButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void noButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}

Categories