问题
I have a C# app with two forms.
The first one is the main form which should always be open.
The second one is a preview pane which the user can enable.
When the user selects to show the preview pane (menu option), the preview pane gets opened.
Which is what I want.
However I want to prevent the preview pane from ever getting the focus. Otherwise if users want to access to menu (which is on the main form) they first click and it looks like nothing is happening (but in fact the focus switches from preview -> main). Only after the second click they can access the menu.
So I thought I had a pretty simple solution:
If the preview ever gets the focus just set the focus to the main form.
However it looks like I cannot access the main form from the preview pane.
To show the preview pane I simply do (on the main form):
QRcodeGenerator.QrCodePreview preview = new QRcodeGenerator.QrCodePreview();
preview.show();
I tried to give the focus back the main form by doing (on the preview window):
private void QrCodePreview_GotFocus(object sender, EventArgs e)
{
QrCodeGenerator.QrCodeSampleApp.focus();
}
But as stated it looks like I cannot access it.
回答1:
youll need to pass the instance of the mainform to the child form. So create a property on the preview form that you set before you call show. Then access that instance of the main form from the instance of the preview form
回答2:
If you invoke
preview.show();
as
preview.show(this);
you can access the main form inside preview object with preview.Parent.
回答3:
You could try,
For Form1 do,
public static Form1 Current;
public Form1()
{
InitializeComponent();
Current = this;
}
Then from preview form,
Form1.Current.Focus();
回答4:
use ShowDialog() to start preview, then the next line after calling ShowDialog() call this.Focus()
来源:https://stackoverflow.com/questions/7207165/giving-focus-back-to-main-form