我开发了一个C#脚本来打开一个XLS文件,解析它并创建一个XML验证它们的文件列表.
该程序的每个主要步骤都记录如下:
Console.WriteLine("Step Creating Xml 1... DONE!)
Console.WriteLine("Step Validating Xml 1... DONE!)
Run Code Online (Sandbox Code Playgroud)
该XLS文件路径是当前硬编码和我创建Windows窗体一个微小的GUI,允许用户选择XLS文件并读取通过在节目进行的步骤TextBox.
我在创建按钮打开文件对话框以选择XSL文件时没有任何问题但是,一旦选中,我很困惑如何编写部件代码以向用户显示程序的步骤信息.
哪个是完成此任务的最常用方法,使核心程序GUI不可知?
小智 5
如其他答案所述,引发GUI处理显示日志文本的事件.这是一个完整的例子:
1)首先考虑事件带有什么信息,并扩展EventArgs类以定义参数事件类.我想要公开一个作为日志文本的字符串:
public class LogEventArgs : EventArgs
{
public string messageEvent {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
2)为简单起见,假设您的MyApplication类公开了您想要的业务方法.我们将从这里定义并举办活动.日志记录将是引发日志事件的私有方法.
public class MyApplication
{
public void BusinessMethod(){
this.Logging("first");
System.Threading.Thread.Sleep(1000);
this.Logging("second");
System.Threading.Thread.Sleep(3000);
this.Logging("third");
}
}
Run Code Online (Sandbox Code Playgroud)
3)实施事件提升.对于句柄事件,我们使用委托,这既是在接收器(您的GUI)中必须实现哪些方法声明来使用事件的描述,也是指向接收器方法的指针.我们声明事件OnLogging.在Inside Logging方法中,我们使用日志消息引发设置参数的事件.我们必须检查非null事件处理程序,因为如果事件没有侦听器,则句柄将为null(指向接收方事件使用者方法的空指针).
public delegate void OnLoggingEventHandler(object sender, LogEventArgs e);
public event OnLoggingEventHandler OnLogging;
private void Logging(string message)
{
LogEventArgs logMessage = new LogEventArgs();
logMessage.messageEvent = message;
if (OnLogging != null)
{
OnLogging(this, logMessage);
}
}
Run Code Online (Sandbox Code Playgroud)
4)现在我们必须实现事件的监听器和使用它的方法.假设有一个窗口表单,其中包含一个启动应用程序业务方法的按钮和一个显示日志消息的文本框.这是没有事件监听器和消费者的表单.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyApplication myApp = new MyApplication();
myApp.BusinessMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
5)我们定义一个消费者方法,用于处理在文本框中写入事件所引发的日志消息的事件.当然,该方法具有与委托相同的签名.
private void MyApplication_OnLogging(object sender, LogEventArgs e)
{
this.textBox1.AppendText(e.messageEvent + "\n");
}
Run Code Online (Sandbox Code Playgroud)
6)使用C#native操作符,我们将OnLogging事件绑定到事件使用者.
private void button1_Click(object sender, EventArgs e)
{
MyApplication myApp = new MyApplication();
myApp.OnLogging += new MyApplication.OnLoggingEventHandler(MyApplication_OnLogging);
myApp.BusinessMethod();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1284 次 |
| 最近记录: |