[英]How can i call a method with parameter of form1 from form2 and plot on chart on form1
[英]How to call a method from Form2 in Form 1
我在表格2中有一個方法
public void set_location(int lx, int ly)
{
this.Location = new Point(lx, ly);
}
發生此事件時需要從Form1調用哪個
private void Form1_LocationChanged(object sender, EventArgs e)
{
loc_x = this.Location.X;
loc_y = this.Location.Y;
}
我將Form2初始化為新線程
private void Form1_Load(object sender, EventArgs e)
{
Thread newThread = new Thread((ThreadStart)delegate { Application.Run(new Form2()); });
newThread.Start();
}
我如何調用方法set_location(x,y); 來自Form1嗎?
首先,第二個線程沒有任何好處。
最簡單的方法是在form2的構造函數中傳遞對form1的引用
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;
}
然后您可以正常引用其屬性
this.Parent.Form1_LocationChanged(this, null);
為了回應您的評論,請在您的form1中也保留對Form2的引用,然后調用
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);
}
請告訴我這項工作
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);
}
}
更新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;
}
或在新的Thread LINK中運行方法的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.