如何从库中的函数获取Windows窗体中的用户输入

本文关键字:Windows 窗体 用户 输入 获取 函数 | 更新日期: 2023-09-27 18:16:35

我有一个执行各种任务的类库。我希望这些任务中的一些发生在响应用户输入从Windows窗体。到目前为止,我所尝试的是在库中设置输入接口,如下所示:

public interface IInputter
{
    string sendInput();
}

以以下形式实现接口:

 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()函数向库函数发送输入。

我敢肯定,必须有一个更"内置"的方式来建立一个数据流,可以从一个库的接口实现的形式内访问;我错过了什么?

如何从库中的函数获取Windows窗体中的用户输入

您的表单是交互式的,因此您的界面将更有意义公开事件:

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);
}