winform如何在后台访问控件。 我在项目中中引入了System.Windows.Forms,然后用单例模式实现的一个listbox日志记录功能不过在多线程访问的时候有时候还是会出问题。大侠帮忙看一下,下面代码。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Windows.Forms;using System.Drawing;namespace Common{ /// <summary> /// 日志工具 /// </summary> public class LogUtil { public static LogUtil Instance = new LogUtil(); private LogUtil() { } public void PrintErrorMessage(string message) { this.RunThread(message); } public void PrintLog(string message) { this.RunThread(message); } private void RunThread(string message) { WaitCallback wc = new WaitCallback(SetLogValue); ThreadPool.QueueUserWorkItem(wc, FormatUtil.GetCurrentTime() + " " + message); } private void SetLogValue(object message) { Form form = Form.ActiveForm; form.Invoke(new Action(delegate() { ListBox listBox = form.Controls["ltbLog"] as ListBox; // 记录一千行日志 if (listBox.Items.Count > 1000) { listBox.Items.Clear(); } listBox.Items.Add(message.ToString()); listBox.SelectedIndex = listBox.Items.Count - 1; listBox.ClearSelected(); })); } }} form.Invoke(new Action(delegate()这一行报未处理NullReferenceException。 Form form = Form.ActiveForm;调试看看form是否等于null没有再去掉new Action(看看form.Invoke(delegate() { 是啊,所以说现在的问题演变成了如何在后台获取Form窗体,我猜想可能是Form窗体失去焦点所以到了Form.ActiveForm获取不到了。 解决了Form form = Form.ActiveForm;改成Form form = Application.OpenForms[0];完美解决~~~ 问一个经典的winform下treeview的checkbox问题 vs 连接远程数据库出错 导出到Excel问题 ZedGraph,画图,横坐标显示日期的问题 生成XML问题 请介绍一下.NET下调用COM+的文章和书籍,谢谢! .net中有什么好的类似j2ee项目的开源代码吗? 写的一个组件在asp.net程序中使用没问题,现在在windowFrom程序中使用,发生异常,实在不知怎么解决,请帮忙 如何用javascript得到treeview所选节点的ID? 怎么取消TreeView分支点击的链接? 高手进(高分),c#正则获取网页指定内容 关于XML序列化的问题
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;namespace Common
{
/// <summary>
/// 日志工具
/// </summary>
public class LogUtil
{
public static LogUtil Instance = new LogUtil(); private LogUtil() { } public void PrintErrorMessage(string message)
{
this.RunThread(message);
} public void PrintLog(string message)
{
this.RunThread(message);
} private void RunThread(string message)
{
WaitCallback wc = new WaitCallback(SetLogValue);
ThreadPool.QueueUserWorkItem(wc, FormatUtil.GetCurrentTime() + " " + message);
} private void SetLogValue(object message)
{
Form form = Form.ActiveForm;
form.Invoke(new Action(delegate()
{
ListBox listBox = form.Controls["ltbLog"] as ListBox;
// 记录一千行日志
if (listBox.Items.Count > 1000)
{
listBox.Items.Clear();
}
listBox.Items.Add(message.ToString());
listBox.SelectedIndex = listBox.Items.Count - 1;
listBox.ClearSelected();
}));
}
}
}
调试看看form是否等于null
没有再去掉new Action(看看
form.Invoke(delegate()
{
Form form = Form.ActiveForm;改成Form form = Application.OpenForms[0];
完美解决~~~