Call MouseEventHandler from another form - c#

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

Related

how to pass parameters to forms c#

I seem to be able to pass the parameter to the form from the program, but then how do i access the variable in the buttons routines. I have put the two sub routines Main() and Start up which would run the form1. and then I have put the namespace of the form.
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
StartUp();
}
static void StartUp()
{
bool mode = false;
Application.Run(new Form1());
//bool playermode = GetPlayerMode();
}
namespace PencilProject
{
public partial class Form1 : Form
{
private static bool modebool;
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
modebool = true;
Close();
}
private void button2_Click(object sender, EventArgs e)
{
modebool = false;
Close();
}
}
}
You can use DialogResult to have a "return value", some sort:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
StartUp();
}
static void StartUp()
{
Form1 frm = new Form1()
Application.Run(frm);
bool mode = frm.DialogResult == DialogResult.Yes;
//bool playermode = GetPlayerMode();
}
namespace PencilProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Yes;
Close();
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.No;
Close();
}
}
}
You even can assign the DialogResult value to the buttons in the designer.
Try this:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var f = new Form1();
f.Mode = false;
Application.Run(f);
bool playerMode = f.Mode;
}
}
And:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public bool Mode = false;
private void button1_Click(object sender, EventArgs e)
{
this.Mode = true;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Mode = false;
this.Close();
}
}
This works fine for me getting bool playerMode set based on the button I click.

How to call a method from Form2 in Form 1

I have a method in Form 2
public void set_location(int lx, int ly)
{
this.Location = new Point(lx, ly);
}
Which need to be called from Form1, when this event happens
private void Form1_LocationChanged(object sender, EventArgs e)
{
loc_x = this.Location.X;
loc_y = this.Location.Y;
}
I Initialize Form2 as a new thread
private void Form1_Load(object sender, EventArgs e)
{
Thread newThread = new Thread((ThreadStart)delegate { Application.Run(new Form2()); });
newThread.Start();
}
How do i call method set_location(x,y); from Form1 ?
Firstly, there isn't any benefit by the second thread.
The easiest way would be to pass a reference to your form1 in form2's constructor
private void Form1_Load(object sender, EventArgs e)
{
Form2 form2 =new Form2();
form2.Show(this);
}
private Form1 Parent {get;set;}
public Form2(Form1 form)
{
this.Parent = form;
}
Then you can reference its properties as normal
this.Parent.Form1_LocationChanged(this, null);
In response to your comment, maintain a reference to Form2 in your form1 also and then just call that
private void Form1_LocationChanged(object sender, EventArgs e)
{
...
this.form2.set_location(loc_x, loc_y);
}
public static void set_location(int lx, int ly)
{
this.Location = new Point(lx, ly);
}
please tell me if this work
Program.cs
static class Program
{
public static Form GlobalMainForm;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
GlobalMainForm = new Form1();
Application.Run(GlobalMainForm);
}
}
Form1.cs
public partial class Form1 : Form
{
public Form2 Form2GlobalInstance { get; set; }
public Form1()
{
InitializeComponent();
Form2GlobalInstance = new Form2();
Thread newThread = new Thread((ThreadStart)delegate { Application.Run(Form2GlobalInstance); });
newThread.Start();
Load += delegate
{
var frm2Location = Form2GlobalInstance.GetLocation();
MessageBox.Show("location.x=" + frm2Location.X + " location.y=" + frm2Location.Y);
};
}
}
Form2.cs
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Point GetLocation()
{
return new Point(Location.X, Location.Y);
}
private void Form2_Load(object sender, EventArgs e)
{
MessageBox.Show("location.x=" + Program.GlobalMainForm.Location.X + " location.y=" + Program.GlobalMainForm.Location.Y);
}
}
Update 1:
static class Program
{
public static Form MainForm;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainForm = new Form1();
Application.Run(MainForm);
}
}
From2:
public void Form1_LocationChanged(object sender, EventArgs e)
{
loc_x =Program.MainForm.Location.X;
loc_y = Program.MainForm.Location.Y;
}
OR
Ways to run a method in a new Thread
LINK

Disable timer from another form in 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;

Can not Focus() onto a Form?

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.

Call to a Superclass function which alters a component (label)

If a Superclass has a function A() which changes a Label to "Hello World". How can I get a subclass to call A() with the same result? As of now, I get no compile error, but the text won't change!
Example code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FunctionA("Hello");
}
public void FunctionA(string s)
{
label1.Text = s;
}
private void button2_Click(object sender, EventArgs e)
{
Test t = new Test();
}
}
class Test : Form1
{
public Test()
{
FunctionA("World");
}
}
Both the Forms must be having their own Label control to display messages. You might be using one Label to show the message which is not part of displaying Form.
I am not sure what are to trying to achieve but why don't you just pass the Label control to FunctionA to modify the message this way:
public void FunctionA(ref Label lbl, string s)
{
lbl.Text = s;
}
ADDED: You can do it this way:
First creating the instance of FormA.
static void Main()
{
//...
FormA frmA = new FormA();
Application.Run(frmA);
}
Passing the instance of FormA to FormB by exposing a parameterized constructor for any manipulation in FormA from within FormB.
FormB frmB = new FormB(frmA);
//...
public partial class FormB : Form
{
public FormB()
{
InitializeComponent();
}
//parameterized constructor
public FormB(FormA obj)
{
FormA = obj;
InitializeComponent();
}
public FormA FormA { get; set; }
}
Instantiate your forms before running the main form. Assign the form1 reference to form2
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 mainForm = new Form1();
new Form2() { Form1 = mainForm }.Show();
Application.Run(mainForm);
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public Form1 Form1 { get; set; }
private void button1_Click(object sender, EventArgs e)
{
this.Form1.Update("World");
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Update("Hello");
}
public void Update(string text)
{
this.label1.Text = text;
}
}

Categories