I can't believe it,this works in my other application,but in this one,which has similiar structure - it doesn't!
public string ListAdd
{
set
{
if (listView1.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
listView1.Items.Add(value);
});
}
else
{
listView1.Items.Add(value);
}
}
}
The way I call it:
var formz = Form.ActiveForm as Form1;
if (formz != null)
formz.ListAdd = "asdasdasdasd";
If I call it from the function where I receive packet(I want to put it on the listView) over TCP - Nothing happens,but If I call it in that same class where I initialize WinSock - it works.
Where could the problem be?
EDIT: I just debugged the application ,formz is null at the place I call it(receive function). Why is it null there,but not at any other place?
-
If ActiveForm is returning null then you might not have an active form or it is not of type Form1. You are using "as Form1", so if you have a Form2 which is active then formz will be set to null.
Can you pass formz into the function instead of calling ActiveForm?
John : I have only one form,and I use async(WSAAsyncSelect()) to do my connections. No,I cant assign Form1 to a var that hasn't been initialized yet.Daniel Brückner : So what does Form.ActiveForm return? Null or a form of a type other than Form1?John : null //Comment.length = 15; -
I do not think, it will solve your problem, but have you thought about using the following pattern to do the invoke? I consider it much more readable. Create this extension method.
public static class ControlExtension { public static void ThreadSafeInvoke(this Control control, MethodInvoker method) { if (control != null) { if (control.InvokeRequired) { control.Invoke(method); } else { method.Invoke(); } } } }And then you can perform thread safe method calls like this.
Form form = new Form(); form.ThreadSafeInvoke(() => form.Text = "ThreadSafeInvoke");Or multiple calls at once.
form.ThreadSafeInvoke(() => { form.Text = "ThreadSafeInvoke"; form.Visible = true; form.WindowState = FormWindowState.Maximized; });UPDATE
So the problem is clearly
Form.ActiveFormreturningnull.- There is no active form at the moment of the call.
- The thread has no permission to get the active form - MSDN states that UIPermission is required.
0 comments:
Post a Comment