如何使用'Gorkem Gencay' InputDialog从另一个类调用它? 修改:插入所有代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace InputDialog
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static DialogResult ShowInputDialog(ref string input)
{
System.Drawing.Size size = new System.Drawing.Size(200, 70);
Form inputBox = new Form();
inputBox.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
inputBox.ClientSize = size;
inputBox.Text = "Name";
System.Windows.Forms.TextBox textBox = new TextBox();
textBox.Size = new System.Drawing.Size(size.Width - 10, 23);
textBox.Location = new System.Drawing.Point(5, 5);
textBox.Text = input;
inputBox.StartPosition = FormStartPosition.CenterParent;
inputBox.Controls.Add(textBox);
Button okButton = new Button();
okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
okButton.Name = "okButton";
okButton.Size = new System.Drawing.Size(75, 23);
okButton.Text = "&OK";
okButton.Location = new System.Drawing.Point(size.Width - 80 - 80, 39);
inputBox.Controls.Add(okButton);
Button cancelButton = new Button();
cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
cancelButton.Name = "cancelButton";
cancelButton.Size = new System.Drawing.Size(75, 23);
cancelButton.Text = "&Cancel";
cancelButton.Location = new System.Drawing.Point(size.Width - 80, 39);
inputBox.Controls.Add(cancelButton);
inputBox.AcceptButton = okButton;
inputBox.CancelButton = cancelButton;
DialogResult result = inputBox.ShowDialog();
input = textBox.Text;
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
string input = "hede";
ShowInputDialog(ref input);
}
}
}
我正在尝试以下而不是使用私有void Form1_Load(对象发件人,EventArgs e),但不起作用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InputDialog
{
class Class1
{
Form1 frm = new Form1();
string input = "hede";
frm.ShowInputDialog(ref input);
}
}
答案 0 :(得分:1)
将if
方法定义为static,因此在调用它时需要使用类名而不是对象名。假设在ShowInputDialog
类中定义了ShowInputDialog
,您应该按如下方式调用它:
Form1
顺便说一下,该方法定义为string input = "hede";
Form1.ShowInputDialog(ref input);
,因此您必须将其设为private
或public
。
internal
定义也有错误。您无法从程序上下文中调用过程代码(Class1
)。定义一个方法并将对话框调用代码放在这个方法中:
frm.ShowInputDialog(ref input);