Change value from in Parent Form from Child Form - c#

I tried different solutions but had no luck... I don't know how to handle this. Following problem:
I have a main form (Form1) and a child form (splashScreen).
The code in my splashScreen:
public splashScreen()
{
InitializeComponent();
}
public splashScreen(Form1 frm1)
{
form1 = frm1;
InitializeComponent();
}
private static splashScreen m_instance = null;
private static object m_instanceLock = new object();
public static splashScreen GetInstance()
{
lock (m_instanceLock)
{
if (m_instance == null)
{
m_instance = new splashScreen();
}
}
return m_instance;
}
In my Form1 I'm creating a new thread and starting my splashScreen. The way I'm calling controls in my splashScreen is the following:
splashScreen splashObj = splashScreen.GetInstance();
if (splashObj.InvokeRequired)
{
splashObj.Invoke((MethodInvoker)delegate()
{
splashObj.Show();
}
);
}
else
{
splashObj.Show();
}
Now the splashScreen gets started when my Form1 is working and shows the current process. On the splashScreen I have a button "Cancel". When I click on that button I want to change a variable "killProc" - which is in my Form1- to "true" so that the work in Form1 can be stopped through a return statement when at some point "if(killProc)" returns true.
How do I change the variable in my Form1 through my splashScreen or is there even a better way?

In the GetInstance method use the splashScreen(Form1 frm1) constructor to constructs an instance. They you have the reference to your parent from SplashScreen, which you could use the set property.
public static splashScreen GetInstance(Form1 frm1)
{
lock (m_instanceLock)
{
if (m_instance == null)
{
m_instance = new splashScreen(frm1);
}
}
return m_instance;
}
So, from SplashScreen
form1.killProc = true;

Related

C# - Edit Form Label using Static Method

public static void Monitor0()
{
bool ToMineOrNot = Backend.ToMineOrNot;
while (ToMineOrNot)
{
Form1 temp = new Form1();
Form1.NonStaticDelegate = new Action(temp.setHashRate);
Form1.NonStaticDelegate();
Backend.hps = 0;
Thread.Sleep(1000);
}
if (ToMineOrNot == false)
{
}
}
public void setHashRate()
{
hashrate.Text = Backend.hps.ToString();
}
I have to get the Static Void to call the non Static Void, i have to have Monitor0 Static because it has to be Run in a Thread, and setHashRate() has to be Non-static to edit the label (It's a Windows form):
Thread thread = new Thread(Monitor0);
thread.Start();
Does anybody know how i could Do that? and I cant just do this because the label won't be changed:
Form1 form = new Form();
form.label1.Text = "text"

Splashscreen - Accessing Label and Progressbar

I have some trouble accessing the ProgressBar and a certain Label in from my splashScreen. I made an own Form for the screen. In my Form1 I have the following method:
private void sign_Click(object sender, EventArgs e)
{
splashScreen splScreen = new splashScreen();
Thread thrd = new Thread(new ThreadStart(loadingScreenStart));
thrd.Start();
splScreen.percentage.Text = "0%";
var logIn = new LogIn(this);
logIn.checkUserInput(this);
thrd.Abort();
}
public void loadingScreenStart()
{
Application.Run(new splashScreen());
}
In my LogIn class I did:
public String checkUserInput(object sender)
{
splashScreen splScreen = new splashScreen();
//won't change my Label and PrpgressBar
I know it's probably because I create a new instance of the Form so it's empty but how to do this right? I don't know... Hope someone can help me.
Same requirement I too had where I need to use the same object but was having a limitation where i cannot use the static class. For that i have created a static object of the class and using lock. Try if it solves your requirement.
private static splashScreen m_instance = null;
private static object m_instanceLock = new object();
public static splashScreen GetInstance()
{
lock (m_instanceLock)
{
if (m_instance == null)
{
m_instance = new splashScreen();
}
}
return m_instance;
}
And whenever you want to create the object or access the already created object, you just need to give as:
SomeClass someobj= SomeClass.GetInstance();

Form instance members and static member

I have a formdlg which can be accessed from two 2 forms
For button click on Form1, it needs to be instance- can have multiple formdlg
But from the other place, I would need only a single instance of formdlg
Any ideas
Thank u
Following is an example code of the class which can provide the answer for you.
class formdlg
{
static formdlg instance;
public static formdlg GetInstance()
{
if (instance == null)
instance = new formdlg();
return instance;
}
}
Since the constructor is public you can call new in the Form1 to get multiple instances anytime you want.
In form2 use the static function GetInstance to retreive the single instance everytime.
Hope this helps.
Simply,
Using Singleton
using System;
public class myForm : Form
{
private static myForm Current;
private myForm() {}
public static myForm Instance
{
get
{
if (Current == null)
{
Current = new myForm();
}
return Current;
}
}
}

Can I only call static functions from a form to another?

I have 2 forms connected to a database, LoadDocument form and a Fom1 that is the primary form. In LoadDocument I get document names out of my database, and when I close LoadDocument I send the document id to Form1 so I can retrieve its content there.
The only problem is that if i make a function in Form1, called public void showContent() my LoadDocument can't call it because it's not static, and if I make it static, I get problems creating radioButtons.
public partial class Form1 : Form
{
public void showTasks()
{
radioButtons = new RadioButton[numberOfTasks];
for (int i = 0; i < numberOfTasks; ++i)
{
radioButtons[i] = new RadioButton();
radioButtons[i].Text = "Task " + (i+1);
radioButtons[i].Location = new System.Drawing.Point(
10, 10 + i * 20);
groupBox1.Controls.Add(radioButtons[i]);
radioButtons[i].Click += new EventHandler(this.radioButtons_Click);
}
}
}
Is there any way I can call this function from LoadDocument without making it static? Do I have to make LoadDocument dynamic, and in that case how?
EDIT: I guess this piece of code would be quite relevant:
private LoadDocument m_form1;
private bool m_underConstruction = false;
private void ShowLoadDocument()
{
if (m_underConstruction)
{
// We're about to show it anyway
return;
}
m_underConstruction = true;
try
{
if (m_form1 == null)
{
m_form1 = new LoadDocument();
// m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);
m_form1.Show();
}
}
finally
{
m_underConstruction = false;
}
m_form1.BringToFront();
m_form1.Activate();
}
I'm not sure about the control flow and the co-existence of the two forms, but you could pass the instance of Form1 to LoadDocument and call the method directly on that object. Like:
public class LoadDocument : Form {
private Form1 form1;
public LoadDocument(Form1 form1) {
this.form1 = form1;
}
// later
public void Method() {
form1.showTasks();
}
}
public class Form1 : Form {
public void SomeMethod() {
LoadDocument doc = new LoadDocument(this);
doc.Show();
}
}
You don't need to make it static, but you need to have a reference to Form1 to call it. You can pass this reference to the constructor of LoadDocument when you create it:
public class Form1 : Form
{
...
LoadDocument loadDocument = new LoadDocument(this);
loadDocument.ShowDialog();
...
}
public class LoadDocument : Form
{
private readonly Form1 _form1;
public LoadDocument(Form1 form1)
{
_form1 = form1;
InitializeComponent();
}
...
_form1.showTasks();
...
}
You can call the showContent method on an instance of Form1.
I understand that the LoadDocument form is created from Form1. Pass the instance of Form1 to the LoadDocument constructor. That way, you'll be able to do form1WhoCreatedMe.ShowContent() somewhere in LoadDocument.
The dynamic keyword won't help you there. dynamic is not the contrary of static.

How to avoid multiple instances of windows form in c#

How to avoid multiple instances of windows form in c# ?? i want only one instance of the form running. Because there are chances of opening the same form from many pages of my application.
implement the Singleton pattern
an example: CodeProject: Simple Singleton Forms (ok, it's in VB.NET, but just to give you a clue)
Yes, it has singleton pattern,
Code to create a singleton object,
public partial class Form2 : Form
{
.....
private static Form2 inst;
public static Form2 GetForm
{
get
{
if (inst == null || inst.IsDisposed)
inst = new Form2();
return inst;
}
}
....
}
Invoke/Show this form,
Form2.GetForm.Show();
When you display the dialog simply use .ShowDialog(); instead of .Show();
One solution I applied to my project in order to bring this form again in the foreground is:
private bool checkWindowOpen(string windowName)
{
for (int i = 0; i < Application.OpenForms.Count; i++)
{
if (Application.OpenForms[i].Name.Equals(windowName))
{
Application.OpenForms[i].BringToFront();
return false;
}
}
return true;
}
windowName is essentially the class name of your Windows Form and
return value can be used for not creating a new form instance.
If your system has the possibility of showing the same type of form for different instance data then you could create a checking system that iterates all existing open forms, looking for a unique instance data identifier and then re-display any found form.
e.g. having a form class 'CustomerDetails' which contains a public property 'CustomerUniqueID':
foreach(Form f in CurrentlyDisplayedForms)
{
CustomerDetails details = f as CustomerDetails;
if((details != null) && (details.CustomerUniqueUD == myCustomerID))
{
details.BringToFront();
}
else
{
CustomerDetails newDetail = new CustomerDetails(myCustomerID);
}
}
We also use the same mechanism to automatically force refreshes of data binding where a customer's data has been edited and saved.
Here is my solution in ShowForm() :
private void ShowForm(Type typeofForm, string sCaption)
{
Form fOpen = GetOpenForm(typeofForm);
Form fNew = fOpen;
if (fNew == null)
fNew = (Form)CreateNewInstanceOfType(typeofForm);
else
if (fNew.IsDisposed)
fNew = (Form)CreateNewInstanceOfType(typeofForm);
if (fOpen == null)
{
fNew.Text = sCaption;
fNew.ControlBox = true;
fNew.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
fNew.MaximizeBox = false;
fNew.MinimizeBox = false;
// for MdiParent
//if (f1.MdiParent == null)
// f1.MdiParent = CProject.mFMain;
fNew.StartPosition = FormStartPosition.Manual;
fNew.Left = 0;
fNew.Top = 0;
ShowMsg("Ready");
}
fNew.Show();
fNew.Focus();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowForm(typeof(FAboutBox), "About");
}
private Form GetOpenForm(Type typeofForm)
{
FormCollection fc = Application.OpenForms;
foreach (Form f1 in fc)
if (f1.GetType() == typeofForm)
return f1;
return null;
}
private object CreateNewInstanceOfType(Type typeofAny)
{
return Activator.CreateInstance(typeofAny);
}
public void ShowMsg(string sMsg)
{
lblStatus.Text = sMsg;
if (lblStatus.ForeColor != SystemColors.ControlText)
lblStatus.ForeColor = SystemColors.ControlText;
}
check this link :
using System;
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
Try this code
Public class MyClass
{
//Create a variable named
public static int count = 0;
//Then increment count variable in constructor
MyClass()
{
count++;
}
}
While creating the object for the above class 'MyClass' check the count value greater than 1
class AnotherClass
{
public void Event()
{
if(ClassName.Count <= 1)
{
ClassName classname=new ClassName();
}
}
}
Here's a simple way to do it.
Check if the form is null, or has been disposed. If that's true we create a new instance of the form.
Otherwise we just show the already running form.
Form form;
private void btnDesktop_Click(object sender, EventArgs e)
{
if (form == null || desktop.IsDisposed)
{
form = new Form();
form.Show();
}
else
{
form.WindowState = FormWindowState.Normal;
}
}
private static MyForm _myForm;
internal static MyForm form
{
get
{
if (_myForm == null)
{
_myForm = new MyForm();
}
return _myForm;
}
}
public MyForm()
{
InitializeComponent();
_myForm = this;
}
private void MyForm_FormClosed(object sender, FormClosedEventArgs e)
{
_myForm = null;
}
Singletons are not object-oriented. They are simply the object version of global variables. What you can do is to make the constructor of the Form class private, so nobody can accidentally create one of these. Then call in reflection, convert the ctor to public and make sure you create one and only one instance of it.
You can check the existing processes prior to opening the form:
using System.Diagnostics;
bool ApplicationAlreadyStarted()
{
return Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length == 0;
}
I don't know if the GetProcessesByName method is affected by UAC or other security measures.

Categories

Resources