【发布时间】:2018-09-25 11:37:10
【问题描述】:
我正在学习使用 PtGrey 相机的 API。
我有以下公司提供的用于设备到达和移除的类示例。
Class SystemEventListener: ManagedInterfaceEvent
{
private IManagedSystem system;
public SystemEventListener(IManagedSystem sys) { system = sys; }
protected override void OnDeviceArrival(UInt64 serialNumber)
{
int count = system.GetCameras().Count;
Console.WriteLine("System event listener:");
Console.WriteLine("\tThere {0} {1} {2} on the system.", (count == 1 ? "is" : "are"), count, (count == 1 ? "device" : "devices"));
}
protected override void OnDeviceRemoval(UInt64 serialNumber)
{
int count = system.GetCameras().Count;
Console.WriteLine("System event listener:");
Console.WriteLine("\tThere {0} {1} {2} on the system.", (count == 1 ? "is" : "are"), count, (count == 1 ? "device" : "devices"));
}
}
我正在尝试将其适应我的获胜形式环境。在努力从这个类更新 GUI 之后,我设法按照链接 here 更新文本框。但是,它涉及修改 program.cs 文件。
我的问题是如何从另一个类中的这些事件更新文本框,最好不接触 Program.cs。
我确实尝试过使用委托/事件等,但每次都在我的主窗体 (Form1) 实例上遇到空引用异常。我肯定做错了什么。
下面是我当前的实现,但我希望有另一种方法,但不修改 program.cs。
程序.cs
public static Form1 MainForm;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainForm = new Form1();
Application.Run(MainForm);
}
Form1.cs
public Form1()
{
InitializeComponent();
SystemEventListener systemEventListener = new SystemEventListener(system);
system.RegisterInterfaceEvent(systemEventListener);
}
private void AppendTextBox(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(AppendTextBox), new object[] { value });
return;
}
textBoxCamProperties.AppendText(DateTime.Now.ToString("h:mm:ss tt") + "-" + value + Environment.NewLine);
}
public class SystemEventListener : ManagedInterfaceEvent
{
private IManagedSystem system;
public SystemEventListener(IManagedSystem sys) { system = sys; }
protected override void OnDeviceArrival(UInt64 serialNumber)
{
//int count = system.GetCameras().Count;
Program.MainForm.AppendTextBox("Device attached\r\n");
}
protected override void OnDeviceRemoval(UInt64 serialNumber)
{
//int count = system.GetCameras().Count;
Program.MainForm.AppendTextBox("Device removed\r\n");
}
}
谢谢。
更新:向#Handbag Crab 致敬!我可以在不接触 Program.cs 的情况下使用他的方法。 :-)
有人也可以告诉我如何在这种特殊情况下正确使用事件/委托吗?
干杯,非常感谢! :-)
【问题讨论】:
-
由于您已经在构造函数中使用(注册接口),因此第一个事件可能在构造函数结束之前被触发,并且
Program.MainForm中的值仍然是null。尝试仅在表单的OnLoad函数中注册事件。 -
嗨,#Julo 感谢您的帮助。我确实尝试过 Form1_Load 事件,但无济于事。
标签: c# winforms desktop-application