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"
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;
Hi I have a use case where I am supposed to use C# Web Browser inside a form and get some data from it. However as we know the C# browser runs under STA hence I have created an instance of SmartThread with single thread architecture.
On some events from an MVC app I am supposed to invoke the web browser and get the result. When the browser is instantiated at that moment I can invoke any JavaScript method, however when I wait for an event in MVC and invoke on event the SmartThread doesn't seems to invoke the webbrowser.
Here is my below code please help me.
public class FormBrowser
{
public static Form1 form1 = null;
public static SmartThreadPool smartThreadPool;
public static void initialise()
{
if (smartThreadPool == null)
{
STPStartInfo stpStartInfo = new STPStartInfo();
stpStartInfo.StartSuspended = true;
stpStartInfo.ApartmentState = ApartmentState.STA;
stpStartInfo.MaxWorkerThreads = 1;
smartThreadPool = new SmartThreadPool(stpStartInfo);
var ab = smartThreadPool.QueueWorkItem(new WorkItemCallback(initForm), "line");
smartThreadPool.Start();
//smartThreadPool.Shutdown();
}
}
public static object initForm(object msg)
{
var id = Thread.CurrentThread.ManagedThreadId;
form1 = new Form1();
System.Windows.Forms.Application.Run(form1);
return null;
}
public static void redraw()
{
var id = Thread.CurrentThread.ManagedThreadId;
smartThreadPool.QueueWorkItem(new WorkItemCallback(rd), "line");
}
public static object rd(object msg)
{
var id = Thread.CurrentThread.ManagedThreadId;
form1.webBrowser1.Document.InvokeScript("startDrawing");
return null;
}
}
On calling initialise() method SmartThread will create a thread pool and then creates a Form instance which holds a Web Browser. Next when any event occures from client say he request for a latest data I have to call method redraw() and which should internally call rd() but that never happens.
Please help me to fix this, if I am missing something let me know.
The below code worked for me.
public class FormBrowser
{
public static Form1 form1 = null;
public static SmartThreadPool smartThreadPool;
public static SynchronizationContext ctx;
public static string html;
public static void initialise()
{
if (smartThreadPool == null)
{
STPStartInfo stpStartInfo = new STPStartInfo();
stpStartInfo.StartSuspended = false;
stpStartInfo.ApartmentState = ApartmentState.STA;
stpStartInfo.MaxWorkerThreads = 1;
smartThreadPool = new SmartThreadPool(stpStartInfo);
var ab = smartThreadPool.QueueWorkItem(new WorkItemCallback(initForm), "line");
smartThreadPool.Start();
//smartThreadPool.Shutdown();
}
}
public static object initForm(object msg)
{
var id = Thread.CurrentThread.ManagedThreadId;
form1 = new Form1();
ctx = WindowsFormsSynchronizationContext.Current;
System.Windows.Forms.Application.Run(form1);
return null;
}
public static string redraw(string chartType)
{
ctx.Send(rd, chartType);
return html;
}
public static void rd(object chartType)
{
var id = Thread.CurrentThread.ManagedThreadId;
html = (string)form1.webBrowser1.Document.InvokeScript("drawChart", new object[] { chartType });
}
}
If SmartThreadPool used along with the SynchronizationContext works well. However using SynchronizationContext alone or SmartThreadPool alone won't solve the issue.
Im new to .net and this is also my first post here so apologies in advance for any newb mistakes I may be doing:)
Background of the problem.
I’m working on a C# project and as part of it I have to store windows form data onto a database. I am using a data class “person” to transport the windows form data to a class responsible for accessing the database on the windows forms behalf. I wish to use the Singleton pattern on the windows forms code to prevent multiple instances of the window from existing.
Problem
In the save buttons event handling code I wish to create a “Person” object, populate it with user entered values and send it to be saved onto the database. The problem occurs here. The “Person” object does not get populated!
I’ve tried doing this in another form where I have not modified the code to accommodate the singleton pattern and that works.
So what am I doing wrong here? Is there a way for me to still keep the singleton pattern and make it work?
Window Form Code
namespace AgTrain
{
public partial class CreateAdmin : Form
{
private static CreateAdmin instance;
private CreateAdmin()
{
InitializeComponent();
}
private void CreateAdmin_Load(object sender, EventArgs e)
{
}
public static CreateAdmin getInstance()
{
if(instance==null)
{
instance = new CreateAdmin();
instance.InitializeComponent();
}
return instance;
}
public void makeInstanceNull()
{
instance = null;
}
private void button1_Click(object sender, EventArgs e)
{
Person personToBeSaved = new Person();
PersonDAO personDAO = new PersonDAO();
personToBeSaved.FirstName = textBox1.Text;
personToBeSaved.LastName = textBox2.Text;
personToBeSaved.Address = textBox3.Text;
personToBeSaved.TelNo = textBox4.Text;
personToBeSaved.UserName = textBox5.Text;
personToBeSaved.Password = textBox6.Text;
personToBeSaved.UserType = "admin";
personDAO.addPerson(personToBeSaved);
}
}
}
Caller Code
private void createAdminToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateAdmin creAdmin = CreateAdmin.getInstance();
creAdmin.Closed += (s, ex) => { creAdmin.makeInstanceNull(); };
creAdmin.MdiParent=this;
creAdmin.Show();
}
Thanks.
Dumidu
You are calling InitializeComponent twice.
Try that:
private static CreateAdmin _instance;
public static CreateAdmin Instance
{
get { return _instance ?? (_instance = new CreateAdmin()); }
}
In my opionion is thefiloe's solution the cleanest, but there is a further possibility to introduce (effective) singletons in C#:
public static readonly CreateAdmin Instance = new CreateAdmin();
Client Code:
CreateAdmin.Instance.DoSomething()
But as already mentioned I recommend thefiloe's way!
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.