how to use run two processes on visual studio - c#

I am writing a game in XNA, and I have the login screen, which is windows form, and the game itself. I need to go from the login screen to the game, but when I try it says that i can't run more then one thred at the time. how can i solve this?
this is the login screen code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ProtoType
{
public partial class SighIn : Form
{
public SighIn()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if ((textBox1.Text.Equals("Developer")) && (textBox2.Text.Equals("poxus17")))
{
using (Game1 game = new Game1())
{
game.Run();
}
}
}
}
}

The XNA Game.Run method executes Application.Run which provides a message pump for the primary thread (UI thread).
At the point in time where your form is running and gets a button click, Application.Run is already executing (possibly through Form.ShowDialog). You cannot have two message pumps in the same thread, at the same time.
The solution is to allow Application.Run to finish, then call Game.Run.
Something like this:
Form form = new SignIn();
if (form.ShowDialog() == DialogResult.OK)
{
if (form.UserName =="Developer" && form.Password == "poxus17")
{
using (Game1 game = new Game1())
{
game.Run();
}
}
}
Now your form's button click handler can copy the textbox fields to properties (UserName, and Password) and set this.DialogResult = DialogResult.OK. This will close the form, completing the message pump started by ShowDialog, then, after verification, start a new message pump with Game.Run.

Related

Visual C# - Changing button's background image programmatically

So I'm trying to make a simple program in Visual C# that counts the number of "Connected Devices", which can be seen as the amount of buttons clicked.
The code should check which button was clicked and change it's background image. It should also update the count and label on the form.
First of all, here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Device_Storage
{
public partial class Form1 : Form
{
int totalDevices = 0;
public Form1()
{
InitializeComponent();
}
private void addDevice(object sender, EventArgs e)
{
try
{
Button clickedBtn = sender as Button;
Image add_image = Properties.Resources.addDevice;
Image remove_image = Properties.Resources.removeDevice;
if (clickedBtn.BackgroundImage == Properties.Resources.addDevice)
{
clickedBtn.BackgroundImage = remove_image;
totalDevices++;
}
else if (clickedBtn.BackgroundImage == Properties.Resources.removeDevice)
{
clickedBtn.BackgroundImage = add_image;
totalDevices--;
}
updateLabel();
} catch (Exception ex)
{
MessageBox.Show(ex.Message, "An Error Occured");
}
}
private void updateLabel()
{
label1.Text = "Connected devices: " + totalDevices;
}
}
}
(I didn't change any of the using statements yet, I usually do that when I'm finished or am 100% sure I won't be using the namespace)
I can't find anything wrong with the code myself and Visual Studio (2015) doesn't give an error.
When I click a button (there are 36 total buttons) nothing happens, the label doesn't update, the image doesn't change, nothing. I don't even get an error, the program doesn't crash.
If anyone can see what I did wrong and can help me fix it that would be really appreciated.
(Edit: My resources folder contains 2 png files, "addDevice.png" and "removeDevice.png")
(New info: all buttons start with the background image "addDevice.png" as to represent an empty slot)

C# Textbox properties do not update

I have a simple form with a text box, a command button and a couple of timers. The only purpose of the form is to advise the user what is happening. The program executes all the code as required EXCEPT for the textbox changes. I know the code to implement the textbox changes is executed because the form and the command button properties change as required.
I have added this.refresh and this.textbox1.refresh to no avail.
I am new to C# and most of the time I do not have Visual Studios available, so your assistance would be most appreciated. I have read other posts on this topic and probably the answer has already been given, but I have not understood the solution.
The simplified code is given below:
//PROGRAM.CS
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using WindowsFormsApplication1;
namespace PostBinaryFile
{
static class Program
{
/// The main entry point for the application.
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));
}
}
}
//FORM1.CS
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string sUrl;
string sFileName;
string sCorNo;
public Form1(string[] args)
{
sUrl = args[0];
sFileName = args[1];
sCorNo = args[2];
InitializeComponent();
timer1.Enabled = true;
timer1.Start();
timer2.Enabled = true;
timer2.Start();
}
public void PostCode()
{
InitializeComponent();
string sToken;
string sPath;
const string boundary = "----WebKitFormBoundaryePkpFF7tjBAqx29L";
try
{
//Do all general code work here.
//Alter form to show successful post to web
this.button1.Visible = true;
this.button1.Enabled = true;
this.BackColor = System.Drawing.Color.FromArgb(189,194,241);
this.textBox1.Text = sCorNo + " Outlook file saved to FuseDMS."; // this code is executed but is not reflected on the Form
this.textBox1.BackColor= System.Drawing.Color.FromArgb(189,194,241); // this code is executed but is not reflected on the Form
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
timer1.Enabled = false;
PostCode();
}
private void timer2_Tick(object sender, EventArgs e)
{
timer2.Stop();
timer2.Enabled = false;
this.textBox1.Text = "Saving Message " + sCorNo + ".";
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
As #DavidG pointed out, you should not call InitializeComponent() periodically or even more then once, do it as the first thing in the constructor.
This is because any controls and properties that you add/set from the designer are created and initialized in this method.
Another thing to point out is Timer.Enabled = true and Timer.Start() effectively do the same thing
From: System.Windows.Forms.Timer.Enabled
Calling the Start method is the same as setting Enabled to true. Likewise, calling the Stop method is the same as setting Enabled to false.
Both timers namely timer1 and timer2 fire asynchronously and run on separate threads which are completely independent of each other. Even if timer2's tick event would be setting/refreshing the text appropriately through below code:
this.textBox1.Text = "Saving Message " + sCorNo + ".";
you can never say with guarantee that it will happen only after timer1's tick event has completed the execution of its callback method. In all likelyhood your above code is setting the text property of a dangling text box instance as your InitializeComponent function (being called from timer1's tick event) must be reinstantiating a new instance of all the form controls.
Your call to InitializeComponent function in PostCode method which gets called from tick event of timer1's tick event isn't right as it resets all the instances of form controls to new ones. It should be called only once in the constructor of the form. Just remove that piece of code and you should be good. Your PostCode function should actually look like this after you get rid of that piece of code:
public void PostCode()
{
string sToken;
string sPath;
const string boundary = "----WebKitFormBoundaryePkpFF7tjBAqx29L";
try
{
//Do all general code work here.
//Alter form to show successful post to web
this.button1.Visible = true;
this.button1.Enabled = true;
this.BackColor = System.Drawing.Color.FromArgb(189,194,241);
this.textBox1.Text = sCorNo + " Outlook file saved to FuseDMS."; // this code is executed but is not reflected on the Form
this.textBox1.BackColor= System.Drawing.Color.FromArgb(189,194,241); // this code is executed but is not reflected on the Form
}

Command Line Argument c#

I have a standalone example program which when executed gives a terminal to get the input as "0" and then shows another window which is essentially the camera function.
program for camera which intakes the command line arguments:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using mv.impact.acquire;
#if USE_DISPLAY
using mv.impact.acquire.display;
#endif // #if USE_DISPLAY
using mv.impact.acquire.examples.helper;
namespace SW_FormsApplication3
{
class ContinousCapture
{
public static void StartCamera(string[] args)
{
//Acquire camera image and display it on window
}//End Method
}//End class
}//End namespace
My toolstrip button to invoke the method:
private void toolStripButton2_Click(object sender, EventArgs e)
{
ContinousCapture.StartCamera();
}
I want to implement the same in my application but in my case, I should click a button on the form (toolstrip button) so that I can have the image window show up. How can I achieve this, meaning how to invoke a method that takes in command line args ?
I have already tried, ContinousCapture.StartCamera(null); I have resolved the problem with PDB file but not able to figure out why the console doesnt show up.
Simple as that ContinousCapture.StartCamera(null);

C# Thread error

So im attempting to create a auto typer. And the problem is if i spam the message, And click the application to stop the spam it just freezes up. I as then told i need to use Threads. So i had a read around and this is what i came up with:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace tf2trade
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public bool started = true;
private void spam()
{
string test = text1.Text;
Thread.Sleep(2000);
while (started == false)
{
foreach (char c in test)
{
SendKeys.Send(c.ToString());
}
SendKeys.Send("{ENTER}");
}
}
Thread test = new Thread(spam);
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void submit_Click(object sender, EventArgs e)
{
if (started == true)
{
started = false;
submit.Text = "Stop";
submit.Refresh();
spam();
}
else
{
started = true;
submit.Text = "Start";
}
}
}
}
Now this code gives me the error:
A field initializer cannot reference the non-static field, method, or property 'tf2trade.Form1.spam()'
What did i do wrong? :(
Thanks in advance,
Alana.
Honestly I wouldn't waste your time troubleshooting this error. Instead, consider using one of the existing approaches to writing multi-threaded applications in .NET . The technology you use will depend on the type of problem you are trying to solve. For short/quick tasks consider using:
thread pool
.net task library
If you are creating a "long" running task you could create 1 or more native threads, but I wouldn't recommend doing this until you have a better understanding of what you are doing. There are a lot of pitfalls. For example, A lot of developers think more threads equals better performance... this is not true.
REFERENCES
thread pool:
http://msdn.microsoft.com/en-us/library/system.threading.threadpool(v=vs.110).aspx
tasks: http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx
native thread: http://msdn.microsoft.com/en-us/library/system.threading.thread(v=vs.110).aspx

Why is the program form not loading when accessing file?

With the below code, I've tested it out and the loading of the form works fine standalone, but when the program goes to check if a file exists, the form doesn't load properly and I'm at a loss as to what to do. Is there another method of checking to see if a file exists that I could use in this instance?
EDIT I've made a new 'startup' form to run the file exists check, but it still doesn't work. Again the form loads, but the contents of the form don't and the form itself freezes.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Diagnostics;
using System.Windows.Input;
namespace program1
{
public partial class Startup : Form
{
public Startup()
{
InitializeComponent();
}
private void Startup_Load(object sender, EventArgs e)
{
notifyIcons norm = new notifyIcons();
Settings set = new Settings();
set.Show();
string curFile = Environment.CurrentDirectory + "\\age.txt";
if (File.Exists(curFile))
{
norm.Show();
this.Close();
}
else
{
set.Show();
for (;;)
{
if (File.Exists(curFile)) norm.Show(); this.Close();
Application.DoEvents();
}
}
}
}
}
I have no idea what this code is supposed to do.. but I can tell you why its not working.
while (ageFileExists)
That is never false. Therefore, your loop will continually loop... forever. You need to set it false somehow in the loop. I have no idea what sort of rules govern that though.
The reason the form doesn't load is because the loop never exits.. and so the message loop that makes the window do anything can never continue processing window messages.
If you can give more context around what you're trying to do I could help you with a proper solution. As it stands though, I can only see the problem.
while(ageFileExists)
{
if (File.Exists(curFile)) ageFileExists = true;
set.WindowState = FormWindowState.Normal;
}
If that file exists you have an infinite loop. You never set ageFileExists to false and that loop does nothing at all. And where does that label go? I seriously doubt you need to be using goto. Your code doesn't make much sense as it stands.
By using the following code in the main form, it seemed to work a treat! I think the critical part was Application.DoEvents();
Thanks for all of your assistance
InitializeComponent();
set.Show();
set.WindowState = FormWindowState.Minimized;
string curFile = Environment.CurrentDirectory + "\\age.txt";
if (File.Exists(curFile)) goto Labelx;
set.WindowState = FormWindowState.Normal;
for (; ; ) { Application.DoEvents(); if (File.Exists(curFile)) break; }
set.WindowState = FormWindowState.Minimized;
Labelx:TextReader reader = File.OpenText(Environment.CurrentDirectory + "\\age.txt");

Categories

Resources