c# call windows form from static function - c#

I have to add a item in the listBox1 from a static function, but it doens't work because of the static^^; is it possible to call windows forms (like the listBox1) from a static function in c#?
what i want to do:
public static void ListBoxTest()
{
listBox1.Items.Add("something");
}

You cannot access non-static methods inside the static method without creating an instance, else you can use something like the following, by Changing the function signature :
public static void ListBoxTest(ListBox listBox1)
{
listBox1.Items.Add("something");
}
and call the function as:
ListBoxTest(listBox1);

You can try this;
private static Form1 _instance;
public Form1()
{
InitializeComponent();
_instance = this;
}
public static void ListBoxTest()
{
_instance.listBox1.Items.Add("something");
}

Related

Invoke of a UserControl doesn't work

I have a form (MainPage) and I set a UserControl in it some times, So I write a method in that form like this to invoke:
delegate void containerPanelCallback(UIPart uiPart);
public void IncludeUIPart(UIPart uiPart)
{
if (this.containerPanel.InvokeRequired)
{
containerPanelCallback d = new containerPanelCallback(IncludeUIPart);
containerPanel.Invoke(d, new object[] { uiPart });
}
else
{
containerPanel.Controls.Clear();
containerPanel.Controls.Add(uiPart);
}
uiPart.Size = this.containerPanel.Size;
uiPart.Dock = DockStyle.Fill;
}
UIPart class inherit from UserControl that my UserControls inherit from UIPart.
This method and invoke launched like this:
public class myClass
{
...
private static MainPage _frmMain;
private static myUIPart6 UIP6;
...
public static void aMethod(/* Some arguments */)
{
UIP6 = new myUIPart6 { /* Some settings of properties */ };
_frmMain.IncludeUIPart(UIP6);
_frmMain.Show(); /*Throws an error*/
}
...
}
The error is:
Cross-thread operation not valid: Control 'MainPage' accessed from a thread other than the thread it was created on.
I found many questions and many answers here about this error, But I can't figure it out why it is throwing at _frmMain.Show();?, Should I invoke something else? Or Am I in a wrong way? Is it related to creation of Handle of my UserControl?
Try adding the following code:
public static void aMethodCaller(){
if (_frmMain.InvokeRequired)
_frmMain.Invoke(new Action(aMethod));
else
aMethod();
}
and replace all references to aMethod() in your code to aMethodCaller()
Below is the sample code:
class Foo
{
static Form _frmMain;
public static void aMethod()
{
_frmMain.Show();
}
public static void aMethodCaller()
{
if (_frmMain.InvokeRequired)
_frmMain.Invoke(new Action(aMethod));
else
aMethod();
}
}
The _frmMain.Show() isn't guarded by any invocation requirement check. So you're probably calling it in a background thread.

Access to listbox in static method

I have one static method which I call from another class when I need update data in listbox. But then I need scroll listbox to last item. Here is code:
public static void updateMessages()
{
MyDatasCurentUser.Clear();//clear messages from previewous user from datas
foreach (var items in UniDB.returnlistOfMessagesData(IdOfChoosenUser, MainContentPage.myID))
{
_mydataCurentUser.Add(new BindingData
{
MessengerReadTime = new DateTime(items.readTime.Year, items.readTime.Month, items.readTime.Day, items.readTime.Hour, items.readTime.Minute, 0),
MessengeFullName = items.senderName,
MessengerTime = new DateTime(items.sendTime.Year, items.sendTime.Month, items.sendTime.Day, items.sendTime.Hour, items.sendTime.Minute, 0).ToString("dd.MM.yyyy - HH:mm"),
MessengerMessage = items.message,
MessengerIsFromMe = items.isFromMe,
});
}
lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
}
But I get error cannot access to non static field in static context at this: lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
Is there any way how I can do this lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last()); when is method updateMessages() called?
If you have a non static method of one class:
class Form1
{
public void UpdateMessages()
{
// ...
lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
}
}
And you want to call it from an object of a different class, that object will need a reference to the first object. A common solution is to pass the reference to the first object into the constructor of the second:
class OtherClass
{
Form1 _form;
OtherClass(Form1 form)
{
_form = form;
}
void Method()
{
//can access the methods of the other object
_form.UpdateMessages();
}
}
Alternatively you could pass the object in later:
class OtherClass
{
public void Method(Form1 form)
{
form.UpdateMessages();
}
}

Access static object from other instance

I have a Program class which has:
private static ClientBase objClientBase = new ClientBase(new List<RecordType> { RecordType.none }, ModuleType.Monitor);
static void Main(string[] args)
{
objClientBase.Connect(); //IRRELEVANT
objQueueMon = new Main(); //<-INSIDE THIS IS WHERE I WANT TO ACCESS objClientBase
objClientBase.MainModuleThreadManualResetEvent.WaitOne(); //IRRELEVANT
}
This Progam creates a Main class instance as you see:
objQueueMon = new Main();
Notice that they are separated in different files, but the Main class instance is created inside the Program class.
Inside my Program class I want to access that objClientBase.
Do I have to create a constructor method and pass it or make a public access to it?
So what I want to achieve is, inside the Main class, do a objClientBase.FUNCTION
You can do exactly what you just said:
public class Main {
private ClientBase _caller;
public Main (ClientBase caller) {
_caller = caller;
}
}
Or, you can set it later
public class Main {
private ClientBase _caller;
public Main () {
}
// only your assembly sets it
internal SetClientBase(ClientBase cb) {
_caller = cb;
}
// but anyone gets it
// Now you can let some client execute "Function"
public ClientBase Caller {
{return _caller;}
}
}
Just an example
Change the constructor of your Main class to accept a ClientBase object, like this:
public class Main
{
private ClientBase _clientBase;
public Main(ClientBase clientBase)
{
_clientBase = clientBase;
}
public void SomeMethod()
{
// Use ClientBase.FUNCTION here
_clientBase.FUNCTION();
}
}

C# Static Form Added to Project?

I want to create a custom message box for a program so I added a windows form item. I would like it to behave like MessageBox in that it is static and I just call MessageBox.Show(a, b, c, ...). In the forms designer, however, I don't see how I can make it static. Can I just add static to the code? Is there a property setting I'm missing in the designer mode?
Thanks!
MessageBox is not a static class, the Show method however is. Make Show static, in code. E.g.
public class MyMessageBox : Form
{
public static int MyShow()
{
// create instance of your custom message box form
// show it
// return result
}
}
It is a regular class with one method as static which instantiate new instance and act.
public class MyMessageBox
{
public static MyResult Show(params)
{
var myMessageBox = new MyMessageBox();
myMessageBox.Message = params ...
return myMessageBox.ShowDialog();
}
}
Add a static method to your form that displays itself and returns a DialogResult:
public partial class MyMessageBoxForm : Form {
public static DialogResult Show(string message) {
using (MyMessageBoxForm form = new MyMessageBoxForm(message)) {
return form.ShowDialog();
}
private MyMessageBoxForm(string message) {
// do something with message
}
}
If you want create static Form1 for access to it without object reference, you can change Program.cs:
public class Program
{
public static Form1 YourForm;
[STAThread]
static void Main(string[] args)
{
using (Form1 mainForm = new Form1())
{
YourForm = mainForm;
Application.Run(mainForm);
}
YourForm = null;
}
}
and call Form1 class methods from any place of your program:
Program.YouForm.DoAnything();
Do not forget to call Invoke for access from other threads.

Shared (static) classes with events in C#

Here is an example of what I would do in Visual Basic:
Public Class Class1
Public Shared WithEvents Something As New EventClass
Public Shared Sub DoStuff() Handles Something.Test
End Sub
End Class
Public Class EventClass
Public Event Test()
End Class
How do I do this in C#?
I know there is not a Handles clause in C# so I need some function that is called and assign the event handlers there. However, since it's a shared class, there is no constructor; I must put it somewhere outside of a function.
How can it be achieved?
You can use the static constructor...
static readonly EventClass _something;
static Class1()
{
_something = new EventClass();
_something.Test += DoStuff;
}
static void DoStuff()
{
}
Try the following
public static class Class1 {
private static EventClass something;
public static EventClass Something {
get { return something; }
}
static Class1 {
something = new Class1();
something.Test += DoStuff;
}
public static void DoStuff() {
...
}
}

Categories

Resources