visual studio timer ticks displayed? - c#

This is my code for my drag race but I am wondering, I have my timer but how do I place it on a label?
private void tmrRaceTimerNamo_Tick(object sender, EventArgs e)
{
//car speed
pcbCar1Namo.Left = pcbCar1Namo.Left + 10;
pcbCar2Namo.Left = pcbCar2Namo.Left + 4;
pcbCar3Namo.Left = pcbCar3Namo.Left + 5;
pcbCar4Namo.Left = pcbCar4Namo.Left + 7;
//car stops at finish
AllCarsOnFinishNamo();
}
private void AllCarsOnFinishNamo()
{
if (pcbCar1Namo.Left > pcbFininshNamo.Right)
{
pcbCar1Namo.Left = pcbFininshNamo.Right;
}
if (pcbCar2Namo.Left > pcbFininshNamo.Right)
{
pcbCar2Namo.Left = pcbFininshNamo.Right;
tmrRaceTimerNamo.Enabled = false;
}
if (pcbCar3Namo.Left > pcbFininshNamo.Right)
{
pcbCar3Namo.Left = pcbFininshNamo.Right;
}
if (pcbCar4Namo.Left > pcbFininshNamo.Right)
{
pcbCar4Namo.Left = pcbFininshNamo.Right;
}
}
private void btnGoNamo_Click(object sender, EventArgs e)
{
//start of timer
tmrRaceTimerNamo.Enabled = true;
}

You can simply set the label to the value on each tick or update. For example in your tmrRaceTimerNamo_Tick(object sender, EventArgs e) method, you can set the labels text property to the time.

I dont exactly know what you want to show but i think you want to see the fps you are getting while playing your drag race game so here is a function for afps counter
private static int lastTick;
private static int lastFrameRate;
private static int frameRate;
public static int CalculateFrameRate()
{
label.Text = CalculateFrameRate().ToString();
if (System.Environment.TickCount - lastTick >= 1000)
{
lastFrameRate = frameRate;
frameRate = 0;
lastTick = System.Environment.TickCount;
}
frameRate++;
return lastFrameRate;
}

Related

How to use check a Button in another Button statement? c#

I am having a problem . I want to use if statement to check if a button is clicked. For Example:
public void button1_Click(object sender, EventArgs e)
{
while (1)
{
...
...
...
if (Button2 == clicked)
{
break;
}
}
}
But it's not working like this, because the ".click" can only be on the left side of "+=" or "-=". Any idea how i can check if Button2 is clicked?
the code is loking like this: and i want to check button2 to stop the "programm".
the check for the Button2 is nearly at the end of the code ;)
public void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int EmFilterPos;
int ExFilterPos;
string String1;
int[] EmLB = new int[126];
int[] ExLB = new int[126];
int LBEmAnzahl = 0;
int LBEmTot = 0;
int LBExAnzahl = 0;
int LBExTot = 0;
UInt32 C_Zyklen;
UInt32 Zyklen;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_On = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOn;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_Off = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOff;
Roche.DetectionControl2.Device_Filterwheels.fiweGetLBResponse LightBarrier;
string Text = String.Format("Filterrad-Dauertest\r\nGestart am {0:d} um {0:t}\r\n\r\n", DateTime.Now);
System.IO.File.WriteAllText(#"TestLogFile\Filterrad_Dauertest1.txt", Text);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
while (Zyklen <= 20)
{
for (int q=1;q<8;q++)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(q,q);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
for (int w=0;w<7;w++)
{
ExFilterPos = rnd.Next(1,8);
EmFilterPos = rnd.Next(1,8);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
C_Zyklen = Zyklen;
if ((C_Zyklen % 2) < 14)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Init bei: ");
String1 = String.Format("{0,7}",Zyklen);
file.Write(String1);
file.Write(file.NewLine);
}
ExFilterPos = 60;
EmFilterPos = 60;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_On);
while (EmFilterPos != -60)
{
LightBarrier = Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweGetLB();
if (LightBarrier.LBEm == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBEmAnzahl++;
LBEmTot += EmFilterPos;
}
if (LightBarrier.LBEx == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBExAnzahl++;
LBExTot += ExFilterPos;
}
ExFilterPos--;
EmFilterPos--;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
}
EmFilterPos = LBEmTot / LBEmAnzahl;
ExFilterPos = LBExTot / LBExAnzahl;
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Nullstelle Mittelposition Em-Filter: ");
file.Write(EmFilterPos);
file.Write(file.NewLine);
file.Write("Nullstelle Mittelposition Ex-Filter: ");
file.Write(ExFilterPos);
file.Write(file.NewLine);
file.Write(file.NewLine);
}
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_Off);
}
if (Button2 == clicked) // or something like this
break;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Beendet am {0:d} um {0:t}\r\n", DateTime.Now);
}*/
}
Hm...
bool b1clicked = false, b2clicked = false;
public void button2_Click(object sender, EventArgs e)
{
b2clicked = true;
}
public void button1_Click(object sender, EventArgs e)
{
b1clicked = true;
if (b1clicked && b2clicked)
{
//...
}
}
Beside the weird behavior you want..and since you are not using Threads, you have the following options:
Local functions (.Net > 4.7)
private void B_Click(object sender, EventArgs e)
{
bool clickFlag = false;
void Click(object sender2, EventArgs e2)
{
clickFlag = true;
}
b2.Click += Click;
while (!clickFlag)
{
Thread.Sleep(1);
}
b2.Click -= Click;
//Continue with your stuff
}
Threads
Thread newThread;
private void Button1_Click()
{
newThread = new Thread(YourBreakableProcess);
newThread.Start();
}
private void Button2_Click()
{
newThread.Join();
}
private void YourBreakableProcess()
{
//Your breakable process
}
Async methods.
I hope you find a solution. Cheers.
Edit:
Since what you want is to interrupt the process of whatever you are doing, the only option you have is Local fuctions as shown above, if you are not tied to a specific framework version.
BackgroundWorker and check in every step if the button 2 was pressed with the flag thing mentioned in other answer.
Threads, and make a thread.Join when the button 2 is pressed.
Edit 2:
Updated answer with Threads, I will recommend that if you go with this option it is much better to use a BackgroundWorker instead as you will have the whole control of the process breaking it only in the place where it would be fine to break it.
You can achieve this using a flag variable. Declare and initialize flag value to false.On button2 click change flag value to true as follows,
private bool flag= false;
private void button2_Click(object sender, EventArgs e)
{
flag= true;
}
public void button1_Click(object sender, EventArgs e)
{
//Use flag to check whether button 2 has clicked or not
if (flag)
{
}
else
{
}
}

C# How to move element on WFA in direction of mouse click controlling speed with timer

I have been trying to solve this problem for a really long time.
Is it possible to move button on Windows Forms application in C# in direction of click event, but controlling the speed of the movement by a timer function?
Here is my code. Can someone please tell me what am I doing wrong?
namespace juriKlik
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
int otkucaj = 1;
MrdajDugme(otkucaj);
}
private void MrdajDugme(int otkucaj)
{
int a = Convert.ToInt32(label1.Text);
int b = Convert.ToInt32(label2.Text);
int c = Convert.ToInt32(label7.Text);
int d = Convert.ToInt32(label8.Text);
Point p = new Point(c + otkucaj, d);
button1.Location = p;
}
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
label1.Text = Convert.ToString(e.X);
label2.Text = Convert.ToString(e.Y);
label7.Text = Convert.ToString(button1.Location.X);
label8.Text = Convert.ToString(button1.Location.Y);
int a = e.X;
int b = e.Y;
int c = button1.Location.X;
int d = button1.Location.Y;
if(a > c)
{
timer1.Start();
}
}
}
}

How to create the second player/Computer

I am working to create a two player dice game, where the player can either play with another user or the computer. i am having a hard time figuring out how to create a two player game. I am not sure if i have to create separate classes for each user and then create an object of that class to have two separate players or if i just have to create a variable like
static int player = 1;
and assign it to specific areas and use modulus to figure out which player is up.
Also, under my roll_Btn method you will see that i am trying to get it to switch to the next user when the dice rolls a "1" and clear the specified fields, which it does, but the then program ends on me once i try and roll the dice again. See below for my code. thank you for your help and guidance.
public partial class Game : Form
{
public Game()
{
InitializeComponent();
}
static int player = 1;
private void Game_Load(object sender, EventArgs e)
{
oneNameTxt.Text = diceFrm.player1.ToUpper();
twoNameTxt.Text = diceFrm.player2.ToUpper();
}
private void endBtn_Click(object sender, EventArgs e)
{
diceFrm end = new diceFrm();
end.Show();
this.Hide();
}
private void standBtn_Click(object sender, EventArgs e)
{
oneScoreTxt.Text = totalTxt.Text;
}
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = Convert.ToInt32(turnsTxt.Text);
int t2 = t1 + 1;
turnsTxt.Text = t2.ToString();
Random rand = new Random();
int dice = rand.Next(1, 7);
rollTxt.Text = dice.ToString();
int d1 = Convert.ToInt32(totalTxt.Text);
int d2 = d1 + dice;
totalTxt.Text = d2.ToString();
if(dice == 1)
{
player++;
rollTxt.Text = String.Empty;
turnsTxt.Text = String.Empty;
totalTxt.Text = String.Empty;
}
}
private void oneScoreTxt_TextChanged(object sender, EventArgs e)
{
int score1 = Convert.ToInt32(oneScoreTxt.Text);
int score2 = Convert.ToInt32(twoScoreTxt.Text);
if (score1 >= 100 || score2 >= 100)
{
whatLbl.Text = "Winner";
}
else
{
whatLbl.Text = "Turn";
}
}
As Ogul Ozgul said,
private void rollBtn_Click(object sender, EventArgs e)
{
...
if (dice == 1)
{
...
turnsTxt.Text = String.Empty;
...
}
}
When you roll a 1, your turnsTxt.Text = String.Empty, hence when the next time you roll,
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = Convert.ToInt32(turnsTxt.Text); // program crash
...
}
your program will crash horribly.
Solution: I will recommend you use TryParse instead of Convert throughout your code. It will be much more robust.
Eg.
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = 0;
int.TryParse(turnsTxt.Text, out t1)
int t2 = t1 + 1;
turnsTxt.Text = t2.ToString();
...
//rest of your code
}

C#, Constantly monitor battery level

I am designing a program that depends on monitoring the battery level of the computer.
This is the C# code I am using:
PowerStatus pw = SystemInformation.PowerStatus;
if (pw.BatteryLifeRemaining >= 75)
{
//Do stuff here
}
My failed attempt of the while statement, it uses all the CPU which is undesirable.
int i = 1;
while (i == 1)
{
if (pw.BatteryLifeRemaining >= 75)
{
//Do stuff here
}
}
How do I monitor this constantly with an infinite loop so that when it reaches 75% it will execute some code.
Try Timer:
public class Monitoring
{
System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
public Monitoring()
{
timer1.Interval = 1000; //Period of Tick
timer1.Tick += timer1_Tick;
}
private void timer1_Tick(object sender, EventArgs e)
{
CheckBatteryStatus();
}
private void CheckBatteryStatus()
{
PowerStatus pw = SystemInformation.PowerStatus;
if (pw.BatteryLifeRemaining >= 75)
{
//Do stuff here
}
}
}
UPDATE:
There is another way to do your task complete. You can use SystemEvents.PowerModeChanged.
Call it and wait for changes, monitor the changes occured then do your stuff.
static void SystemEvents_PowerModeChanged(object sender, Microsoft.Win32.PowerModeChangedEventArgs e)
{
if (e.Mode == Microsoft.Win32.PowerModes.StatusChange)
{
if (pw.BatteryLifeRemaining >= 75)
{
//Do stuff here
}
}
}
While loop will cause your UI to response poor and the application will get crashed. You can solve this by using many ways. Please check out the below code snippet will help your needs.
public delegate void DoAsync();
private void button1_Click(object sender, EventArgs e)
{
DoAsync async = new DoAsync(GetBatteryDetails);
async.BeginInvoke(null, null);
}
public void GetBatteryDetails()
{
int i = 0;
PowerStatus ps = SystemInformation.PowerStatus;
while (true)
{
if (this.InvokeRequired)
this.Invoke(new Action(() => this.Text = ps.BatteryLifePercent.ToString() + i.ToString()));
else
this.Text = ps.BatteryLifePercent.ToString() + i.ToString();
i++;
}
}
BatteryChargeStatus.Text = SystemInformation.PowerStatus.BatteryChargeStatus.ToString();
BatteryFullLifetime.Text = SystemInformation.PowerStatus.BatteryFullLifetime.ToString();
BatteryLifePercent.Text = SystemInformation.PowerStatus.BatteryLifePercent.ToString();
BatteryLifeRemaining.Text = SystemInformation.PowerStatus.BatteryLifeRemaining.ToString();
PowerLineStatus.Text = SystemInformation.PowerStatus.PowerLineStatus.ToString();
If you want to perform some operation just convert these string values into the integer.

c# programmable selecting dropdown value

I am new at C# and it seems the following code below does not seem to select my combobox value:
private void button1_Click(object sender, EventArgs e)
{
cbPortNumber.SelectedValue = 3;
or
cbPortNumber.setValue("3");
or
cbPortNumber.SelectedIndex = cbPortNumber.FindString("3");
or
cbPortNumber.SelectedIndex = cbPortNumber.Items.IndexOf(cbPortNumber.Items.FindByValue("HDMI 4"));
}
The dropdown looks like this:
All code above does not seem to select HDMI 4 on the list... I dont have any errors but i also don't have it being selected.
Any help would be great!
update showing combobox
UPDATE 2
//
// cbPortNumber
//
this.cbPortNumber.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.cbPortNumber.Enabled = false;
this.cbPortNumber.FormattingEnabled = true;
this.cbPortNumber.Location = new System.Drawing.Point(174, 40);
this.cbPortNumber.Name = "cbPortNumber";
this.cbPortNumber.Size = new System.Drawing.Size(133, 21);
this.cbPortNumber.TabIndex = 11;
this.cbPortNumber.Text = "global_hdmi_port";
this.helpPortNumber.SetToolTip(this.cbPortNumber, "The HDMI port number, to which you connected your USB-CEC adapter.");
this.cbPortNumber.SelectedIndexChanged += new System.EventHandler(this.cbPortNumber_SelectedIndexChanged);
#region Global settings
public CECSettingByte HDMIPort
{
get
{
if (!_settings.ContainsKey(KeyHDMIPort))
{
CECSettingByte setting = new CECSettingByte(KeyHDMIPort, "HDMI port", 1, _changedHandler) { LowerLimit = 1, UpperLimit = 15, EnableSetting = EnableHDMIPortSetting };
setting.Format += delegate(object sender, ListControlConvertEventArgs args)
{
ushort tmp;
if (ushort.TryParse((string)args.Value, out tmp))
args.Value = "HDMI " + args.Value;
};
Load(setting);
_settings[KeyHDMIPort] = setting;
}
return _settings[KeyHDMIPort].AsSettingByte;
}
}
Update 3
And this is what fires the action after selecting something in that dropdown:
private void OnSettingChanged(CECSetting setting, object oldValue, object newValue)
{
if (setting.KeyName == CECSettings.KeyHDMIPort)
{
CECSettingByte byteSetting = setting as CECSettingByte;
if (byteSetting != null)
{
if (!Settings.OverridePhysicalAddress.Value)
Config.HDMIPort = byteSetting.Value;
CECActions.SetConnectedDevice(Settings.ConnectedDevice.Value, byteSetting.Value);
}
}
So this code is working fine for me:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 2;
}
you can not access a ItemSource if there are no items to access. The simple way is to Init the items over the Desinger
( Sory for the nonlocalized IDE ) than you can set the Property SelectedIndex to a Index that exits. The other way is to Add all HDMI items with the Combobox1.Items.Add function.
If you ever used Forms in VB ... its still the same
public Form1()
{
InitializeComponent();
var hdmi = "HDMI";
for (int i = 1; i < 15; i++)
{
comboBox1.Items.Add( hdmi + i);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.Items.Count >= 2)
comboBox1.SelectedIndex = 2;
}

Categories