我有一个执行各种任务的类库。我希望其中一些任务能够响应来自 Windows 窗体的用户输入而发生。到目前为止我所尝试的是在库中设置一个输入界面,如下所示:
public interface IInputter
{
string sendInput();
}
实现接口(interface)的形式:
public partial class Form1 : Form,IInputter
{
string sentText=null;
public Form1()
{
InitializeComponent();
}
public string sendInput()
{
string inputText=sentText;
sentText=null;
return inputText;
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel files (*.xls*)|*.xls*";
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
sentText = ofd.FileName;
}
}
}
从表单代码调用库函数时将表单作为参数传递:
public partial class StartForm : Form
{
public StartForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.Show();
Main main = new Main();
main.main(f1);
}
}
然后从库函数中调用输入函数:
public string main(IInputter inputter)
{
do
{
testBk = inputter.sendInput();
}
while (testBk == null);
return testBk;
}
但是,Form1
尚未完全加载;控件所在的位置只有空白,因此 While
循环只是无限运行,而表单无法通过 IInputter.sendInput()< 将输入发送到库函数
函数。
我确信必须有一种更“内置”的方法来设置可以从接口(interface)以表单实现的库内访问的数据流;我错过了什么?
最佳答案
您的表单是交互式的,因此您的界面会更有意义地公开事件:
public interface IInputter
{
event EventHandler<InputReceivedEventArgs> ReceivedInput;
}
public class InputReceivedEventArgs : EventArgs
{
public InputReceivedEventArgs(string text)
{
this.Text = text;
}
public string Text { get; private set; }
}
public partial class Form1 : Form, IInputter
{
public event EventHandler<InputReceivedEventArgs> ReceivedInput = delegate { };
private void button1_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog { Filter = "Excel files (*.xls*)|*.xls*" };
var dialogResult = dialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
ReceivedInput(this, new InputReceivedEventArgs(ofd.FileName));
sentText = ofd.FileName;
}
}
}
然后,消费:
public string main(IInputter inputter)
{
string receivedInput = null;
inputter.ReceivedInput += (s, e) => YourLibrary.DoSomething(e.Text);
}
关于c# - 如何从库中的函数获取 Windows 窗体中的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16906502/