我想改變進程線程事件火災窗體控件屬性中,我有以下的代碼,但我收到此異常類:委託調用
調用線程不能訪問此對象,因爲不同的 線程擁有它。
代碼:
public partial class main : Window
{
public main()
{
InitializeComponent();
}
public void change()
{
label1.Content = "hello";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
nmap nmap = new nmap(this);
nmap.test("hello");
}
}
class nmap
{
private main _frm;
private Process myprocess;
public nmap(main frm)
{
_frm = frm;
}
public void test(object obj)
{
string s1 = Convert.ToString(obj);
ProcessStartInfo startInfo = new ProcessStartInfo();
myprocess = new Process();
myprocess.StartInfo.FileName = "C:\\nmap\\nmap.exe";
myprocess.EnableRaisingEvents = true;
myprocess.Exited += new EventHandler(myProcess_Exited);
myprocess.Start();
}
private void myProcess_Exited(object sender, System.EventArgs e)
{
try
{
_frm.change();
}
catch{}
}
}
請幫我在這,我想代表調用必須工作
我的項目是一個WPF C#項目。
答案是:
class nmap
{
private main _frm;
private Process myprocess;
public nmap()
{
}
public nmap(main frm)
{
_frm = frm;
}
public void test(object obj)
{
string s1 = Convert.ToString(obj);
ProcessStartInfo startInfo = new ProcessStartInfo();
myprocess = new Process();
myprocess.StartInfo.FileName = "C:\\nmap\\nmap.exe";
//myprocess.StartInfo.CreateNoWindow = true;
myprocess.EnableRaisingEvents = true;
//myprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myprocess.Exited += new EventHandler(myProcess_Exited);
myprocess.Start();
}
private void myProcess_Exited(object sender, System.EventArgs e)
{
try
{
String s;
s = "hello";
_frm.Dispatcher.Invoke(_frm.USD, new Object[] { s });
}
catch{}
}
}
public partial class main : Window
{
public delegate void UpdateStatusDelegate(string value);
public UpdateStatusDelegate USD;
public main()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
USD = new UpdateStatusDelegate(this.AddString);
}
private void AddString(String s)
{
label1.Content = s;
}
public void change()
{
label1.Content = "hello";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
nmap nmap = new nmap(this);
nmap.test("hello");
}
}
嗨哈迪我在WPF工作沒有InvokeRequired方法,但無論如何,我仍然有這個問題!請描述更多謝謝! –
我應該在nmap類或主窗口窗體中使用delegete調用? –
啊,你沒有注意到你提到你在使用WPF。在WPF中,您應該能夠使用Dispatcher.Invoke方法(幾乎)執行相同的操作。 –