我试图从另一种形式调用主窗体中的函数...已经调用一个简单的函数,通过在主窗体中声明它是public static,但我无法调用所需的函数.调用函数:
public static void spotcall()
{
string dial = Registry.CurrentUser.OpenSubKey("SOFTWARE").OpenSubKey("INTERCOMCS").GetValue("DIAL").ToString();
MainForm.txtSendKeys.Text = dial;// Here it asks me for a reference to an object.
foreach (char c in txtSendKeys.Text)
{
sideapp.Keyboard.SendKey(c.ToString(), checkBoxPrivate.Checked);
}
txtSendKeys.Clear();
}
Run Code Online (Sandbox Code Playgroud)
我用来从子表单调用它的过程:
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Hoho";
MainForm.spotcall();
}
Run Code Online (Sandbox Code Playgroud)
我完全承认我缺乏关于C#的一些理论,但是因为它经常发生,我只需要为我的工作做,所以我希望得到帮助,如果我偶然得不到解决方案.谢谢 :)
您无法MainForm
在静态方法中引用控件实例.就像编译器告诉你的那样,你需要一个表单实例来更新TextBoxes之类的东西.没有实例,您尝试更新的值会在哪里?
我不确定如何创建子表单,但是您可以调用方法的一种方法MainForm
是MainForm
直接向子表单提供对您的实例的引用.这可以通过构造函数或一些公共属性.
例如
public class ChildForm : Form {
public MainForm MyParent { get; set; }
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Hoho";
// Now your child can access the instance of MainForm directly
this.MyParent.spotcall();
}
}
Run Code Online (Sandbox Code Playgroud)
假设您正在创建代码ChildForm
内部MainForm
以给孩子一个引用非常简单:
var childForm = new ChildForm();
childForm.MyParent = this; // this is a `MainForm` in this case
childForm.Show();
Run Code Online (Sandbox Code Playgroud)
您还需要创建spotcall
实例方法而不是静态方法,并MainForm
在代码中删除静态引用:
public void spotcall()
{
string dial = Registry.CurrentUser.OpenSubKey("SOFTWARE").OpenSubKey("INTERCOMCS").GetValue("DIAL").ToString();
// Now it no longer asks you for a reference, you have one!
txtSendKeys.Text = dial;
foreach (char c in txtSendKeys.Text)
{
sideapp.Keyboard.SendKey(c.ToString(), checkBoxPrivate.Checked);
}
txtSendKeys.Clear();
}
Run Code Online (Sandbox Code Playgroud)