I tried:
Form myForm = new EULA();
myForm.Show();
this.WindowState = FormWindowState.Minimized;
myForm.BringToFront();
myForm.Activate();
myForm.Focus();
This code brings it to the front, but for some reason I still have to click on the Form for it to have focus, can anyone tell me why?
The form may be focused already, perhaps you want a control inside it (like a textbox or a combo) to be selected instead?
I'll use this code at the form's load method:
private void Form_Load(object sender, System.EventArgs e)
{
controlName.Select();
}
Hi leaf68 just follow my codes. try to figure it out :)
Let say we have MainForm and LoginForm
In our project we have a Static Class we called Program -> The main entry point for the application. as default class to run our projects.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new LoginForm());
if (LoginForm._loginSuccess)
{
var m = new MainForm();
Application.Run(m);
}
else
Application.Exit();
}
public static bool UserLogin() //Add some parameter
{
//You Logic here
LoginForm._loginSuccess = true;
return LoginForm._loginSuccess;
}
}
then this is our LoginForm codes
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}
public static bool _loginSuccess { get; set; }
public event EventHandler Login;
private void loginButton_Click(object sender, EventArgs e)
{
if (Program.UserLogin())
{
Close();
Dispose();
if (Application.OpenForms.Count > 0)
if (Application.OpenForms["MainForm"].Name == "MainForm")
{
Application.OpenForms["MainForm"].WindowState = FormWindowState.Normal;
Application.OpenForms["MainForm"].Enabled = true;
}
if (Login != null)
Login(this, EventArgs.Empty);
}
}
}
then assuming that we successfully Login To MainForm so this is our MainForm codes
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void logOutButton_Click(object sender, EventArgs e)
{
//Hide();
Enabled = false;
WindowState = FormWindowState.Minimized;
var f = new LoginForm();
f.Login += loginShow;
f.Show();
f.Activate();
}
private void loginShow(object sender, EventArgs args)
{
Show();
}
}
I hope it helps you :)
I have a form not visible, so only the tray icon.
I just use:
this.ShowInTaskbar = true;
this.WindowState = FormWindowState.Normal;
this.Activate();
In the above order. Program comes to the front and is activated, meaning typing actually writes in the active field.
This works:
when program appears automatically and
when user selects tray menu item.
Related
In my program, I have two forms: public partial class Form1 : Form,
and a log-in form: public partial class Login : Form. Both within the same namespace
Login window is opened when a Log-in button is clicked on the main window:
public partial class Form1 : Form
{
private void LoginToolStripMenuItem_Click(object sender, EventArgs e) //Login button event
{
LoginWindow = new Login();
LoginWindow.ShowDialog();
LogOutToolStripMenuItem.Enabled = true;
}
}
When the password is entered, I want to enable additional controls for the user, on the main screen.
groupBox2 is invisible by default, now I would like to make it visible:
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e) //Confirm click event
{
if (textBox1.Text == Form1.password) //Here, no trouble accessing a string from the main screen
{
Form1.groupBox2.Visible = true; //********** Here is my problem **********
Form1.LoginWindow.Close();
}
else
{
textBox1.Text = "Incorrect password";
textBox1.SelectAll();
}
}
}
How do I overcome "An object reference is required for the non-static field, method or property 'Form1.groupBox2' problem?
All my controls are already set to public.
I'm reading and reading and can't figure it out, it's driving me mad now.
I'm not expecting a ready solution, just a good explanation.
You can just raise a event on your login form like this:
public partial class Login : Form
{
public EventHandler OnPasswordDone; // declare a event handler
public Login()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == Form1.password)
{
// raise the event to notify main form
OnPasswordDone(this, new EventArgs());
}
else
{
textBox1.Text = "Incorrect password";
textBox1.SelectAll();
}
}
}
And in your main form:
public partial class Form1 : Form
{
private void LoginToolStripMenuItem_Click(object sender, EventArgs e) //Login button event
{
LoginWindow = new Login();
LoginWindow.OnPasswordDone += Login_PasswordDone; // regist your event here
LoginWindow.ShowDialog();
LogOutToolStripMenuItem.Enabled = true;
}
private void Login_PasswordDone(object sender, EventArgs e)
{
//Do what you need to do here like:
groupBox2.Visible = true;
}
}
Since Form1 is not static class , so you should create object of this class then set visible to true like as
Form1 formobj=new Form1();
formobj.groupBox2.Visible = true;
What is the best way to hide the main form on application's startup to show it later?
If I just call the Hide method in the Load event of this form it gives a terrible flash for some time before actually hiding it.
Thanks in advance.
The simplest way is to set Opacity = 0 in the designer. Of course you will want to set it back to 100 at some point later..
Or you may want to use a splash screen, maybe like this:
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Splash splash = new Splash();
splash.Show();
Application.Run();
}
}
With a splash screen:
public partial class Splash : Form
{
public Splash()
{
InitializeComponent();
}
Form1 form1 = new Form1();
private void Splash_Load(object sender, EventArgs e)
{
form1.WindowState = FormWindowState.Minimized;
form1.Hide();
}
}
You can then show it for example when the splash screen is closed:
private void Splash_FormClosed(object sender, FormClosedEventArgs e)
{
form1.Show();
form1.WindowState = FormWindowState.Normal;
}
Which would happen whenever you want or maybe after some time:
public Splash()
{
InitializeComponent();
Timer timer = new Timer();
timer.Interval = 5000;
timer.Enabled = true;
timer.Tick += (s,e) =>{ this.Close();};
}
Since the program is not watching a Form to close we also need to add this to the main form's closed event:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
If you don't want the splash screen to be visible at all you can hide it like this:
public Splash()
{
InitializeComponent();
this.Opacity = 0;
But please make sure you don't leave the users in the blind: When I start a program I want immediate response!!
You can proceed like this:
private void Form1_Load(object sender, EventArgs e)
{
if (Settings.Instance.HideAtStartup)
{
BeginInvoke(new MethodInvoker(delegate
{
Hide();
}));
}
}
An alternative way can be to use the Application.Run(Form) method. You can create the main form with its Visible property initially set to false, and provide no argument to Application.Run() in main loop.
Modify your Program class - this is where the form is created and shown:
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main () {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 frm = new Form1();
frm.Visible = false;
Application.Run();
}
}
Hopefully your adding some sort of user interface?
Hello I am following this post Control timer in form 1 from form 2, C# , response, the problem is that I can not solve it yet, I have a timer on form1, and I need to stop it from form2 try all that I found in this post but still nothing.
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
timer1.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
richTextBox1.AppendText("test\n");
}
}
Form2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//
}
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.Hide();
form1.timer1.Enabled = false;
}
}
anyone can help me ?
Update :
static class Program
{
/// <summary>
/// Punto de entrada principal para la aplicación.
/// </summary>
[STAThread]
public static Form1 MainForm;
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
The problem is that you are creating a new instance of Form1, so that is a different timer than the instance of the form you are looking at. You need to store a reference to the Form1 that is displayed (probably in your Program.Main).
So your Program.Main probably looks like this:
static class Program
{
public static int Main()
{
Form1 form = new Form1();
Application.Run(form);
}
}
You want to store that reference, so modify it as such:
static class Program
{
public static Form1 MainForm;
[STAThread]
public static int Main()
{
MainForm = new Form1(); // THIS IS IMPORTANT
Application.Run(MainForm);
}
}
And then you can use that stored referene in your Form2:
private void button1_Click(object sender, EventArgs e)
{
Program.MainForm.Hide();
Program.MainForm.timer1.Enabled = false;
}
This is a functional solution - personally I would not consider this an optimal solution. I would look at using something along the lines of an Event Aggregator/Broker, but if this is a really simple program without a lot of need for complexity, then this works.
Make sure the timer you need to access is modified as public, because the default modifier will be private.
Use the Properties panel provided by your IDE or use the designer code.
public System.Windows.Forms.Timer timer2;
I've got two forms, with subForm being called/created by a buttonClick in Form1. Right now I can initiate subForm, hide Form1, and then unhide Form1 when subForm is closed. What I'd like to be able to do is:
If user clicks changeform button, check to see if subForm is active but hidden
If no, then initiate subForm, else hide Form1, unhide subForm and pass control to it
If user clicks subForm's changeform button, hide subForm, unhide Form1 and pass control to it
If user clicks the "X" in the upper right corner of the form, then close the application, regardless of which form is active. (Right now, selecting the "X" closes the subForm and opens/unhides Form1.)
I can find solutions that do part of the requirements (and maybe all, I'm just too noob to know). To repeat from my previous question here, the code I have so far is:
Form1
private void countClick(object sender, EventArgs e)
{
this.Hide();
subForm myNewForm = new subForm();
myNewForm.ShowDialog();
this.Show();
countSelect.Checked = false;
}
and subForm
private void totalClick(object sender, EventArgs e)
{
this.Close();
}
This works, but it's not really elegant.
I think the best way to do this is to roll your own ApplicationContext. This allows you full control over the application lifetime without having it being tied to a specific Window. See http://msdn.microsoft.com/en-us/library/ms157901.aspx for more information.
Here's an example:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyApplicationContext());
}
}
public class MyApplicationContext : ApplicationContext
{
public MyApplicationContext()
{
ShowForm1();
}
public void ShowForm1()
{
if (_form2 != null)
_form2.Hide();
if (_form1 == null)
{
_form1 = new Form1(this);
_form1.FormClosed += OnFormClosed;
}
_form1.Show();
MainForm = _form1;
}
public void ShowForm2()
{
if (_form1 != null)
_form1.Hide();
if (_form2 == null)
{
_form2 = new Form2(this);
_form2.FormClosed += OnFormClosed;
}
_form2.Show();
MainForm = _form2;
}
private void OnFormClosed(object sender, FormClosedEventArgs e)
{
if (_form1 != null)
{
_form1.Dispose();
_form1 = null;
}
if (_form2 != null)
{
_form2.Dispose();
_form2 = null;
}
ExitThread();
}
private Form1 _form1;
private Form2 _form2;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Form1(MyApplicationContext context)
: this()
{
_context = context;
}
private void button1_Click(object sender, EventArgs e)
{
if (_context != null)
_context.ShowForm2();
}
private readonly MyApplicationContext _context;
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Form2(MyApplicationContext context)
: this()
{
_context = context;
}
private void button1_Click(object sender, EventArgs e)
{
if (_context != null)
_context.ShowForm1();
}
private readonly MyApplicationContext _context;
}
So we'll start out by going to the child form and creating a new event that can be used to notify the parent when it wants to change forms:
public event Action ChangeForm;
Then we fire the event and hide the child form when it wants to change forms:
private void ChangeForm_Click(object sender, EventArgs e)
{
Hide();
if (ChangeForm != null)
ChangeForm();
}
The parent form needs an instance of the child form as an instance field:
private subForm child = new subForm();
And it needs to initialize it in it's constructor, both adding handlers to the ChangeForm event to show the parent, and to the closed event to close itself:
public Form1()
{
InitializeComponent();
child.ChangeForm += () => Show();
child.FormClosed += (s, args) => Close();
}
Then all that's left is for the parent form to hide itself and show the child when it wants to change forms:
private void ChangeForm_Click(object sender, EventArgs e)
{
Hide();
child.Show();
}
Why not simply setting them to foreground, topmost, and so on ?
And setting them back vice versa ?
---added as comment as proposed
To access MainForm fromsubForm:
Create a constructor in your subForm and a field:
MainForm MainFormRef_Field;
subForm(MainForm MainFormRef)
{
this.MainFormRef_Field = MainFormRef;
}
Now you can access your MainForm using this reference. Like this:
MainFormRef_Field.Show();
MainFormRef_Field.Hide(); //or how ever you want to handle it
To access subForm fromMainForm:
To handle your subForm use the object you created for it. Here:
subForm myNewForm = new subForm();
To close whole application if any of the form closes:
Set a Form_Closing event for both forms:
private void MainForm_Closing(object sender, EventArgs e)
{
Application.Exit();
}
private void subForm_Closing(object sender, EventArgs e)
{
Application.Exit();
}
Note:
I am not writing the whole code for all of your cases. Set the variables, check the conditions. Its all up to you that how code it. All the main points you needed I've provided you the solution of them.
I'm trying to have the owner-form minimize when the modal-form is minimized. But when I minimize the modal-form – it disappears completely. (- I can click on the owner-form.)
How do I solve this?
I have:
public partial class Form1 : Form
{
Form2 frm2 = new Form2();
public Form1()
{
InitializeComponent();
frm2.Owner = this;
}
private void button1_Click(object sender, EventArgs e)
{
frm2.ShowDialog();
}
}
And:
class Form2 : Form
{
Form1 frm1;
FormWindowState ws = new FormWindowState();
public Form2()
{
SizeChanged += new EventHandler(Form2_SizeChanged);
}
void Form2_SizeChanged(object sender, EventArgs e)
{
frm1 = (Form1)Owner;
if (WindowState == FormWindowState.Minimized)
{
ws = frm1.WindowState;
frm1.WindowState = FormWindowState.Minimized;
}
else frm1.WindowState = ws;
}
}
(While trying this, I also ran into this: Modal form doesn't appear in tray until minimized and owner-form is clicked once. How do I make it appear? )
This is by design. As part of the modality contract, showing a dialog disables all the other windows in the application. When the user minimizes the dialog window, there are no windows left that the user can access. Making the app unusable. Winforms ensures this cannot happen by automatically closing the dialog when it gets minimized.
Clearly you'll want to prevent this from happening at all. Set the MinimizeBox property to false. The MaximizeBox property ought to be set to false as well, making both buttons disappear from the window caption. Leaving room for the HelpButton btw.
I don't recall every needing this much code to get modal Windows to work. I'm concerned by your comment 'I can click on the owner form', which leads me to believe that the form is nt being correctly set up as modal. By defintion, modal forms must be dealt with before user control can return to the owner form. Minimizinfg the modal form does not constitute properly 'dealing' with the modal form.
Here is some code that I have used in the past. Notes: passing the owner as parameter in ShowDialog establishes the ownership relationship. While I suspect your code works, I've not used it that way.
Also, when I have done this, I have not put any special code in the modal form, and have also disabled all the button in the upper right corner of the form; thereby insuring that the user cannot close, minimize, or maximize the modal form outside of any buttons I have provided.
public partial class Form1 : Form
{
Form2 frm2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
frm2.ShowDialog(this);
}
}
I hope this helps.
Forms have a property ShowInTaskbar. If it is set to false then the form will never appear on the task bar, even when minimized.
Add a:
Show();
At the end of Form2's event-handler.
I also had the requirement where when minimizing a dialog form it should minimize the application and when restoring the application it should show the dialog again. Here's what I did:
MainForm.cs
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2.Show(this, "Testing 123");
}
}
Form2.cs
public partial class Form2 : Form
{
bool isMinimized;
private Form2()
{
InitializeComponent();
ShowInTaskbar = false;
}
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
if (Owner != null)
{
Owner.Enabled = true;
}
}
private void Form2_Load(object sender, EventArgs e)
{
MinimizeBox = Owner != null;
if (Owner != null)
{
Owner.Enabled = false;
}
}
private void Form2_SizeChanged(object sender, EventArgs e)
{
if (Owner != null)
{
if (WindowState == FormWindowState.Minimized && Owner.WindowState != FormWindowState.Minimized)
{
Owner.Enabled = true;
Owner.WindowState = FormWindowState.Minimized;
isMinimized = true;
}
else if (isMinimized && Owner.WindowState != FormWindowState.Minimized)
{
Owner.Enabled = false;
}
}
}
public static void Show(Form owner, string message)
{
var form2 = new Form2();
form2.label1.Text = message;
if (owner != null)
form2.Show(owner);
else
form2.ShowDialog();
}
}