Disable timer from another form in c# - c#

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;

Related

Updating a c# form while loading a second form

I am having a problem with updating a textbox inside a form in c#, while loading a second form.
I have two forms in my application. form1 loads first then it loads form2.
When form2 loads it should update the the textbox.txt in form1 with some text (in this case: F2:Running), indicating that it has been loaded.
Any kind of help is appreciated, here's the current code:
namespace EditingBox {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
namespace EditingBox {
public partial class Form1: Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
Form2 F2 = new Form2();
Form1 F1 = new Form1();
F2.Show();
textBox1.Select();
textBox1.Refresh();
}
public void textBox1_TextChanged(object sender, EventArgs e) {
}
private void label1_Click(object sender, EventArgs e) {
}
}
}
namespace EditingBox {
public partial class Form2: Form {
public Form2() {
InitializeComponent();
Form1 F1 = new Form1();
F1.textBox1.Select();
F1.textBox1.Text = "F2:Running";
F1.textBox1.Refresh();
}
private void Form2_Load(object sender, EventArgs e) {
Form1 F1 = new Form1();
F1.textBox1.Select();
F1.textBox1.Text = "F2:Running";
F1.textBox1.Refresh();
}
}
}
You need to pass the Form1 this instance from the original form whenever you create it. Currently:
Form1 F1 = new Form1(); is creating a new instance of form1, not the instance which is displayed. Hence all you need to do is add a Form1 form1 to the constructor of form2 and call that constructor whenever you display it:
public Form2(Form1 F1)
{
InitializeComponent();
F1.textBox1.Select();
F1.textBox1.Text = "F2:Running";
F1.textBox1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
Form2 F2 = new Form2(this);
F2.Show();
textBox1.Select();
textBox1.Refresh();
}
You can pass Form1 to Form2 constructor:
namespace EditingBox
{
public partial class Form2 : Form
{
Form1 _form1;
public Form2(Form1 form1)
{
InitializeComponent();
_form1 = form1;
_form1.textBox1.Select();
_form1.textBox1.Text = "F2:Running";
_form1.textBox1.Refresh();
}
private void Form2_Load(object sender, EventArgs e)
{
_form1.textBox1.Select();
_form1.textBox1.Text = "F2:Running";
_form1.textBox1.Refresh();
}
}
}

How to get string data in main form from second from, when button on second form is clicked in C# .net?

At first I thought that it won't be a problem for me, but now I can't figure it out. So,
when I click Button1 in main form, form2 opens. Form2 is simple numeric keyboard, that user can enter some data. On form2 is also Save. When user clicks it, entered value should pass to main form and from that moment some event must happen in main form, which contains data from form2. Could you please give me some example or any kind of help? Thanks!
// code from main form to create form2
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
// Show the settings form
settingsForm.Show();
string val = settingsForm.ReturnValue1;
MessageBox.Show(val);
}
//button save on form2
private void button13_Click(object sender, EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.Close();
//after this, some event should happen in main form !
}
There is a lot of solutions to do what you want; but I think one of these will resolve your problem.
1- Simple and easy: use public properties in Form2, initialize them when buttonSave get clicked, and access them in Form1:
Form2:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
YourDate = "something";
Close();
}
public object YourDate { get; private set; }
}
Form1:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
var f2 = new Form2();
f2.ShowDialog();
var data = f2.YourDate;
}
}
2- A better way, is using events which is more flexible and professional programming friendly:
Form2:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
// create an event of Action<T> which T is your data-type. e.g. in this example I use an object.
public event Action<object> SaveClicked;
// create an event invocator, to invoke event whenever you want
protected virtual void OnSaveClicked(object data){
var handler = SaveClicked;
if (handler != null)
handler(data);
}
private void button1_Click(object sender, EventArgs e){
// prepare your data here, -object, or string, or int, or whatever it is
var data = PrepareYourDataHere;
// invoke the event
OnSaveClicked(data);
Close();
}
}
Form1:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
// create an instance of Form2
var f2 = new Form2();
// add an event listener to SaveClicked event -which we have declared it in Form2
f2.SaveClicked += f2_SaveClicked;
f2.Show();
// or: f2.ShowDialog();
}
void f2_SaveClicked(object obj) {
// get data and use it here...
// any data which you pass in Form2.OnSaveClicked method, will be accessible here
}
}
UPDATE:
If you want to fire some events in form1, just after form2 closed, you can simply add a listener to Form2.FormClosed event:
// code from main form to create form2
private void button1_Click(object sender, EventArgs e) {
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
settingsForm.FormClosed += SettingFormClosed;
// Show the settings form
settingsForm.Show();
string val = settingsForm.ReturnValue1;
MessageBox.Show(val);
}
void SettingFormClosed(object sender, FormClosedEventArgs e) {
// this method will be called automatically when form2 closed
}
here a sample how you can achieve this
//here I suppose that form1 is the mainform
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void UpdateMainForm(string updatedString)
{
//here you can update and invoke methods
//Once called you could raise events in your mainform
}
private void button1_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2(this))
{
form2.ShowDialog();
}
}
}
Form2
public partial class Form2 : Form
{
private Form1 _mainForm1;
public Form2(Form1 mainForm1)
{
InitializeComponent();
_mainForm1 = mainForm1;
}
private void button1_Click(object sender, EventArgs e)
{
_mainForm1.UpdateMainForm( DateTime.Now.ToString());
}
}

C# global/public variables that keeps value

I got a newbie question !
What I have is 3 windows form, named frmMain,frmSub1,frmSub2 for example.
I want a int variable which gets value from processes in frmSub or frmSub2 then used in frmMain for another process.
I explored other QA's before posting this. But none of them satisfied my curiosity. I just saw bunch of codes but I want a meaningful explonation with codes as why/how them works.
Many thanks for suggestions.
Edit :
I don't have any code for this inquiry at all. There is no application yet. I'm at planning phase. Sorry for "no code given". I can write codes after I get the stage of where I need this variable.
you can do something like this:
public class frmMain
{
public static int Vartoshare=100;
private void setvalues()
{
vartoshare=200;
}
}
then in your frmsub2 form you can call
int readvar = frmmain.vartoshare;
Solution 1: you can pass your int variable to New Form Constructor and assign that value in the NewForm constructor.
Try This:
Program.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(0));
}
Form1 Code:
int no = 10;
public Form1(int no)
{
this.no=no;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(no);
this.Hide();
form2.ShowDialog();
}
Form 2: Code
int no;
public Form2(int no)
{
this.no = no;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
no = 20;
Form1 form1 = new Form1(no);
this.Hide();
form1.Show();
}
Solution 2: you can take public static varible in Form1 and access that variable in chid forms using their class names.
Try This:
Form1 Code:
public static int no = 10;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
this.Hide();
form2.ShowDialog();
}
Form 2: Code
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.no = 20; //access Form1 int variable
Form1 form1 = new Form1(no);
this.Hide();
form1.Show();
}

if called window is already running then close it and run newly called window

In my app in several time i have to call a window(class). the work of this window is to show the meaning of a word.when i again call that window a new window shows but the previous one also shows.
I have two form named form1,form2.
Form1 is like that:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
Form2 s = new Form2(a);// it will be called as many time as i click
s.Show();
}
}
Form2 is like that:
public partial class Form2 : Form
{
public Form2(string s)
{
InitializeComponent();
label1.Text = s;
}
}
what i want is that inside form1 if i call form2 it shows but if i call form2 again the previous form2 window will be closed automatically and new form2 window will be shown instead of previous one.
How can i do that????
Here's an example of storing the Form2 reference at class level, as mentioned by the others already:
public partial class Form1 : Form
{
private Form2 f2 = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (f2 != null && !f2.IsDisposed)
{
f2.Dispose();
}
string a = textBox1.Text;
f2 = new Form2(a);
f2.Show();
}
}
I think you should consider using singleton pattern.
You can implement it like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
Form2.ShowMeaning(a);// it will be called as many time as you click
}
}
and Form2
public partial class Form2 : Form
{
private static readonly Form2 _formInstance = new Form2();
private Form2()
{
InitializeComponent();
}
private void LoadMeaning(string s)
{
label1.Text = s;
}
//Override method to prevent disposing the form when closing.
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
this.Hide();
}
public static void ShowMeaning(string s)
{
_formInstance.LoadMeaning(s);
_formInstance.Show();
}
}
Hope it helps.

Call MouseEventHandler from another form

I create a MouseEventHandler in Main form :
public Home()
{
InitializeComponent();
this.KeyPreview = true;
this.MouseMove += new MouseEventHandler(Home_MouseMove);
}
public static void Home_MouseMove(object sender, MouseEventArgs e)
{
bomb.Stop();
bomb.Start();
}
How can I call the MouseEventHandler from another form?
Any other good method?
Fisrt you have to change Home_MouseMove event to non static:
public void Home_MouseMove(object sender, MouseEventArgs e)
{
bomb.Stop();
bomb.Start();
}
Go to program.cs file and change the code from this:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
}
to this code:
static class Program
{
public static FrmMain MainForm;// add this line
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainForm = new FrmMain();// add this line
Application.Run(MainForm);
}
}
now on the form2 you can call the MouseMove in the main form like this:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// call MouseMove event in main form
Program.MainForm.FrmMain_MouseMove(null, null);
}
}
I have tested that. It works.
The code in main form is:
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
public void FrmMain_MouseMove(object sender, MouseEventArgs e)
{
this.label1.Text = DateTime.Now.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
new Form1().Show();
}
}
The Form1 code is:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Program.MainForm.FrmMain_MouseMove(null, null);
}
}
it has one button with click event. When you click the button the mouse move event in main form is raised
Finally the program.cs code is
static class Program
{
public static FrmMain MainForm;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainForm = new FrmMain();
Application.Run(MainForm);
}
}
I have tested it and it words. I can send the project if you want

Categories