After selecting a song in filedrop, the player freezes for a while and then postpones
When re-selecting a song, the player behaves the same
The delay time is about 10 seconds, after which the player works normally again.
The problem is connected with a file drop, or with button 3, when the player starts playing music
Code:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using WMPLib;
namespace Music_Player
{
public partial class Form1 : Form
{
private WMPLib.WindowsMediaPlayer Player;
private Image pauseImage;
private Image playImage;
private bool isPlaying;
public Form1()
{
InitializeComponent();
button3.ImageAlign = ContentAlignment.MiddleCenter;
}
private void Form1_Load(object sender, EventArgs e)
{
Player = new WMPLib.WindowsMediaPlayer();
Player.PlayStateChange += new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange);
Player.MediaError += new WMPLib._WMPOCXEvents_MediaErrorEventHandler(Player_MediaError);
string startPath = Application.StartupPath;
pauseImage = Image.FromFile(Path.Combine(startPath, "pause.png"));
playImage = Image.FromFile(Path.Combine(startPath, "play.png"));
button3.Image = playImage;
}
private void Player_PlayStateChange(int newState)
{
isPlaying = (WMPLib.WMPPlayState)newState == WMPLib.WMPPlayState.wmppsPlaying;
if (isPlaying)
button3.Image = pauseImage;
else
button3.Image = playImage;
}
private void Player_MediaError(object pMediaObject)
{
MessageBox.Show($"Cannot play media file {Player.URL}.");
}
private void button3_Click(object sender, EventArgs e)
{
if (isPlaying)
{
hScrollBar1.Enabled = true;
timer1.Enabled = true;
timer1.Interval = 1000;
Player.controls.pause();
}
else
{
hScrollBar1.Enabled = true;
timer1.Enabled = true;
timer1.Interval = 1000;
Player.controls.play();
}
}
private void button5_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (isPlaying)
Player.controls.pause();
label5.Text = openFileDialog1.SafeFileName;
Player.URL = openFileDialog1.FileName;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
hScrollBar1.Maximum = Convert.ToInt32(Player.currentMedia.duration);
hScrollBar1.Value = Convert.ToInt32(Player.controls.currentPosition);
if (Player != null)
{
int s = (int)Player.currentMedia.duration;
int h = s / 3600;
int m = (s - (h * 3600)) / 60;
s = s - (h * 3600 + m * 60);
label3.Text = String.Format("{0:D}:{1:D2}:{2:D2}", h, m, s);
s = (int)Player.controls.currentPosition;
h = s / 3600;
m = (s - (h * 3600)) / 60;
s = s - (h * 3600 + m * 60);
label2.Text = String.Format("{0:D}:{1:D2}:{2:D2}", h, m, s);
}
else
{
label3.Text = "0:00:00";
label2.Text = "0:00:00";
}
}
private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
Player.controls.currentPosition = hScrollBar1.Value;
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
if (trackBar1.Value == 10)
Player.settings.volume = 100;
if (trackBar1.Value == 9)
Player.settings.volume = 90;
if (trackBar1.Value == 8)
Player.settings.volume = 80;
if (trackBar1.Value == 7)
Player.settings.volume = 70;
if (trackBar1.Value == 6)
Player.settings.volume = 60;
if (trackBar1.Value == 5)
Player.settings.volume = 50;
if (trackBar1.Value == 4)
Player.settings.volume = 40;
if (trackBar1.Value == 3)
Player.settings.volume = 30;
if (trackBar1.Value == 2)
Player.settings.volume = 20;
if (trackBar1.Value == 1)
Player.settings.volume = 10;
if (trackBar1.Value == 0)
Player.settings.volume = 0;
}
}
}
Related
the problem is that you can't assign to timespan milliseconds it's read only.
private void UpdateTime()
{
if (ticksDisplayed > 0)
btnReset.Enabled = true;
richTextBox1.Text = GetTimeString(watch.Elapsed);
optionsfile.SetKey("result", result.ToString());
}
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{
ticksDisplayed += diff;
}
else
{
if (countingDown)
{
ticksDisplayed += diff;
}
else
{
ticksDisplayed -= diff;
}
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
timer1.Enabled = false;
}
ctimeSpan = new TimeSpan(ticksDisplayed);
timeTarget(ctimeSpan);
if (trackBarHours.Value != ctimeSpan.Hours) { trackBarHours.Value = ctimeSpan.Hours; }
if (trackBarMinutes.Value != ctimeSpan.Minutes) { trackBarMinutes.Value = ctimeSpan.Minutes; }
if (trackBarSeconds.Value != ctimeSpan.Seconds) { trackBarSeconds.Value = ctimeSpan.Seconds; }
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}
calling the UpdateTime here
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
saving the timespan milliseconds is not a problem , the problem is how to read it back because you can't assign to ctimeSpan.Milliseconds.
i could save the string.Format variable result again in more places but sometimes result is null if i try to save it in the form1 closed event. so i prefer to save and load back only the ctimeSpan.Milliseconds value in that specific situation.
Editing with the full code of form1 and a screenshot.
Now i'm using the 3 trackBars to save and load the timespan hours,minutes,seconds but because i don't want to add another trackBar for the milliseconds that is the reason i want to save/load the milliseconds separated.
in my application i'm using my own OptionsFile class but it does not matter i want to find the logic and how to save/load the milliseconds separated from the way i'm saving/loading the hours,minutes,seconds.
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.Diagnostics;
using System.IO;
using DannyGeneral;
namespace StopwatchTimer
{
public partial class Form1 : Form
{
private static readonly Stopwatch watch = new Stopwatch();
private long diff = 0, previousTicks = 0, ticksDisplayed = 0;
private OptionsFile optionsfile = new OptionsFile(Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Settings.txt");
private string result;
private bool runOnStart = false;
private bool countingDown = false;
private TimeSpan ctimeSpan;
public Form1()
{
InitializeComponent();
richTextBox1.TabStop = false;
richTextBox1.ReadOnly = true;
richTextBox1.BackColor = Color.White;
richTextBox1.Cursor = Cursors.Arrow;
richTextBox1.Enter += RichTextBox1_Enter;
trackBarHours.Value = Convert.ToInt32(optionsfile.GetKey("trackbarhours"));
trackBarMinutes.Value = Convert.ToInt32(optionsfile.GetKey("trackbarminutes"));
trackBarSeconds.Value = Convert.ToInt32(optionsfile.GetKey("trackbarseconds"));
richTextBox1.Text = optionsfile.GetKey("result");
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
ticksDisplayed = ctimeSpan.Ticks;
radioButton1.Checked = GetBool("radiobutton1");
timeTargetchkbox.Checked = GetBool("timetargetcheckbox");
timeTargetchkboxState();
if (ticksDisplayed > 0 && radioButton1.Checked == false)
radioButton2.Checked = true;
if (ticksDisplayed == 0)
radioButton1.Checked = true;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnPause.Enabled = false;
btnReset.Enabled = false;
}
else
{
btnPause.Enabled = false;
btnReset.Enabled = true;
}
runOnStart = GetBool("runonstart");
if (runOnStart == true)
{
autoRunOnStart.Checked = true;
StartOnRun();
}
else
{
autoRunOnStart.Checked = false;
}
}
private void timeTargetchkboxState()
{
if (timeTargetchkbox.Checked == false)
{
dateTimePicker1.Enabled = false;
}
else
{
dateTimePicker1.Enabled = true;
}
}
private void RichTextBox1_Enter(object sender, EventArgs e)
{
btnStart.Focus();
}
private void UpdateTime()
{
if (ticksDisplayed > 0)
btnReset.Enabled = true;
richTextBox1.Text = GetTimeString(watch.Elapsed);
optionsfile.SetKey("result", result.ToString());
}
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{
ticksDisplayed += diff;
}
else
{
if (countingDown)
{
ticksDisplayed += diff;
}
else
{
ticksDisplayed -= diff;
}
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
timer1.Enabled = false;
}
ctimeSpan = new TimeSpan(ticksDisplayed);
timeTarget(ctimeSpan);
if (trackBarHours.Value != ctimeSpan.Hours) { trackBarHours.Value = ctimeSpan.Hours; }
if (trackBarMinutes.Value != ctimeSpan.Minutes) { trackBarMinutes.Value = ctimeSpan.Minutes; }
if (trackBarSeconds.Value != ctimeSpan.Seconds) { trackBarSeconds.Value = ctimeSpan.Seconds; }
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}
private void timeTarget(TimeSpan ctimeSpan)
{
if (dateTimePicker1.Value.Hour == ctimeSpan.Hours
&& dateTimePicker1.Value.Minute == ctimeSpan.Minutes
&& dateTimePicker1.Value.Second == ctimeSpan.Seconds
&& timeTargetchkbox.Checked == true)
{
//ticksDisplayed = 0;
if (btnPause.Text == "PAUSE")
{
btnPause.Text = "CONTINUE";
watch.Stop();
timer1.Enabled = false;
}
}
else
{
if (btnStart.Text == "STOP")
{
btnPause.Text = "PAUSE";
watch.Start();
timer1.Enabled = true;
}
}
timeTargetchkboxState();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "START")
{
watch.Reset();
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
else
{
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
btnReset.Enabled = false;
trackBarHours.Value = 0;
trackBarMinutes.Value = 0;
trackBarSeconds.Value = 0;
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Reset();
timer1.Enabled = false;
UpdateTime();
}
}
private void btnReset_Click(object sender, EventArgs e)
{
watch.Reset();
diff = 0;
previousTicks = 0;
ticksDisplayed = 0;
trackBarHours.Value = 0;
trackBarMinutes.Value = 0;
trackBarSeconds.Value = 0;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnReset.Enabled = false;
}
else
{
btnReset.Enabled = true;
}
if (radioButton2.Checked && ticksDisplayed == 0)
{
countingDown = true;
radioButton2.Checked = false;
radioButton1.Checked = true;
}
UpdateTime();
}
private void trackBarHours_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan htimeSpan = new TimeSpan(ctimeSpan.Days, trackBarHours.Value, ctimeSpan.Minutes, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
ticksDisplayed = htimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
UpdateTime();
}
private void trackBarMinutes_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan mtimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, trackBarMinutes.Value, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
ticksDisplayed = mtimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
UpdateTime();
}
private void trackBarSeconds_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan stimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, ctimeSpan.Minutes, trackBarSeconds.Value, ctimeSpan.Milliseconds);
ticksDisplayed = stimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
UpdateTime();
}
private void TrackbarsScrollStates()
{
if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
btnReset.Enabled = false;
if (trackBarSeconds.Value > 0 || trackBarHours.Value > 0 || trackBarMinutes.Value > 0)
btnReset.Enabled = true;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
optionsfile.SetKey("radiobutton1", radioButton1.Checked.ToString());
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
}
private void btnPause_Click(object sender, EventArgs e)
{
Pause();
}
private void Pause()
{
if (btnStart.Text == "STOP")
{
if (btnPause.Text == "PAUSE")
{
btnPause.Text = "CONTINUE";
watch.Stop();
timer1.Enabled = false;
}
else
{
btnPause.Text = "PAUSE";
watch.Start();
timer1.Enabled = true;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
private void autoRunOnStart_CheckedChanged(object sender, EventArgs e)
{
if (autoRunOnStart.Checked)
{
runOnStart = true;
}
else
{
runOnStart = false;
}
optionsfile.SetKey("runonstart", runOnStart.ToString());
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
countingDown = false;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
btnStart.Focus();
timeTarget(ctimeSpan);
}
private void timeTargetchkbox_CheckedChanged(object sender, EventArgs e)
{
if (timeTargetchkbox.Checked == false)
{
dateTimePicker1.Enabled = false;
}
else
{
dateTimePicker1.Enabled = true;
}
optionsfile.SetKey("timetargetcheckbox", timeTargetchkbox.Checked.ToString());
}
private void StartOnRun()
{
watch.Reset();
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
private bool GetBool(string keyname)
{
string radiobutton1 = optionsfile.GetKey(keyname);
bool b = false;
if (radiobutton1 != null)
{
bool.TryParse(radiobutton1.Trim(), out b);
}
return b;
}
}
}
and a screenshot showing the application :
I'm going to attempt to generalize as the question doesn't show a clear intent on what is trying to be accomplished and so it's difficult to give a clear answer.
There are many ways to instantiate a new TimeSpan as documented here:
https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=net-7.0#instantiating-a-timespan-value
If I were trying to persist and load a TimeSpan then I would personally look towards using the ticks value.
e.g.
// Create a TimeSpan to test with.
var randomTimer = Stopwatch.StartNew();
Thread.Sleep((new Random()).Next(1000,5000)); // Wait 1 to 5 second to get a meaningful value in the example TimeSpan.
var myTimeSpanToSave = randomTimer.Elapsed;
// Save the total ticks here.
var totalEllapsedTicks = myTimeSpanToSave.Ticks;
// Load total ticks and instantiate a new TimeSpan
var newTimeSpanFromTicks = new TimeSpan(totalEllapsedTicks);
I'm not sure why you would want to modify just the Millisecond portion of a TimeSpan but assuming there is a valid reason then here are a couple of ideas.
Idea 1 - Create a new TimeSpan using the values from the original object and substituting the Millisecond property only.
var customMilliseconds = 123;
var newTimeSpanWithCustomMilliseconds = new TimeSpan(myOriginalTimeSpan.Days, myOriginalTimeSpan.Hours, myOriginalTimeSpan.Minutes, myOriginalTimeSpan.Seconds, customMilliseconds);
Idea 2 - Use Add to clear the current Millisecond value and insert the loaded value.
var customMilliseconds = new TimeSpan(0, 0, 0, 0, 123);
var oldMillisecondValueToRemove = new TimeSpan(0, 0, 0, 0, myOriginalTimeSpan.Milliseconds);
myOriginalTimeSpan.Add(-oldMillisecondValueToRemove);
myOriginalTimeSpan.Add(customMilliseconds);
I having problem on the C# Windows Forms.
I have created a timer and a button to act as a timer lamp.
Now I have created the timer and the timer value can get successfully.
But I dont know why the button backcolor cannot change as the setted on the code.
Below is my whole codes.
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 TimerLamp
{
public partial class Form1 : Form
{
System.Timers.Timer t;
int s, c, x;
String sec;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEvent;
//t.Enabled = true;
}
private void OnTimeEvent(object sender, System.Timers.ElapsedEventArgs e)
{
s += 1;
sec = s.ToString();
if (s == 23)
{
s = 0;
c += 1;
}
TimerTextBox.Invoke((MethodInvoker)(() => TimerTextBox.Text = s.ToString()));
TimerTextBox.Invoke((MethodInvoker)(() => CounterTextBox.Text = c.ToString()));
sec = s.ToString();
}
private void TurnOnLamp_CheckedChanged(object sender, EventArgs e)
{
if (TurnOnLamp.Checked == true)
{
x = Convert.ToInt16(sec);
if (x >= 0 && x <7)
{
btnLamp.BackColor = Color.Green;
}
if (x > 8 && x < 19)
{
btnLamp.BackColor = Color.Red;
}
else if (x >= 19)
{
btnLamp.BackColor = Color.Green;
}
else
{
btnLamp.BackColor = Color.Red;
}
}
if (TurnOnLamp.Checked == false)
{
btnLamp.BackColor = Color.Red;
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "Start")
{
t.Start();
if (c >= 30)
{
MessageBox.Show("Limit reached");
return;
}
btnStart.Text = "Stop";
}
else if (btnStart.Text == "Stop")
{
t.Stop();
btnStart.Text = "Start";
}
}
private void btnLamp_Click(object sender, EventArgs e)
{
}
private void TimerTextBox_TextChanged(object sender, EventArgs e)
{
}
private void CounterTextBox_TextChanged(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Stop();
Application.DoEvents();
}
}
}
Can someone help me to solve this problem?
When you press the button once, it starts counting in the btnLamp_Click class. And when the checkbox is checked, the button blinks as following code.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TimerLamp
{
public partial class Form1 : Form
{
Timer t;
int s, c, x;
String sec;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new Timer();
t.Interval = 1000; //1s
t.Tick += OnTimeEvent;
//t.Enabled = true;
}
private void OnTimeEvent(object sender, EventArgs e)
{
s += 1;
sec = s.ToString();
if (s == 9)
{
s = 0;
c += 1;
}
textBox1.Text = "sec = " + sec;
textBox2.Text = "c = " + c;
if (TurnOnLamp.Checked == true)
{
x = s;
if (x == 0) btnLamp.BackColor = Color.Green;
if (x == 2) btnLamp.BackColor = Color.Red;
if (x == 4) btnLamp.BackColor = Color.Blue;
if( x == 6) btnLamp.BackColor = Color.LightCyan;
}
else
{
btnLamp.BackColor = Color.Gray;
}
}
private void btnLamp_Click(object sender, EventArgs e)
{
if (btnLamp.Text == "Start")
{
t.Start();
if (c >= 2)
{
MessageBox.Show("Limit reached");
t.Stop();
}
btnLamp.Text = "Stop";
}
else if (btnLamp.Text == "Stop")
{
t.Stop();
btnLamp.Text = "Start";
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
t.Stop();
Application.DoEvents();
}
}
}
i have int score = 0; under public partial class Form1 : Form and Im getting error in txtscore.Text = "Score: " + score; and score = 0; in private void RestartHry() does someone know why is that? Or know how to fix that bsc i have no idea. ......................................................................................................................................................................................
namespace Projekt_Havlík
{
public partial class Form1 : Form
{
bool vpravo, vlevo;
int rychlost = 8;
int score = 0;
int minul = 0;
Random rndX = new Random();
Random rndY = new Random();
PictureBox minulcoin = new PictureBox();
public Form1()
{
InitializeComponent();
RestartHry();
}
private void MainGameTimerEvent(object sender, EventArgs e)
{
//naprogramovaní textboxů
txtscore.Text = "Score: " + score;
txtminul.Text = "Minul: " + minul;
//změnění postavy při jízdě do leva/prava
if (vlevo == true && player.Left > 0)
{
player.Left -= 12;
player.Image = Properties.Resources.main_left;
}
if (vpravo == true && player.Left + player.Width <this.ClientSize.Width)
{
player.Left += 12;
player.Image = Properties.Resources.main_right;
}
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = false;
}
if (e.KeyCode == Keys.Right)
{
vpravo = false;
}
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = true;
}
if (e.KeyCode == Keys.Right)
{
vpravo = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void RestartHry()
{
foreach(Control x in this.Controls)
{
if (x is PictureBox &&(string)x.Tag == "coins")
{
x.Top = rndY.Next(80, 300) * -1;
x.Left = rndX.Next(5, this.ClientSize.Width - x.Width);
}
}
player.Left = this.ClientSize.Width / 2;
player.Image = Properties.Resources.main_right;
score = 0;
minul = 0;
rychlost = 8;
vpravo = false;
vlevo = false;
CasovacHry.Start();
}
}
}
Try changing the name of your "score" variable, try calling it like, "myScore", typically if something is ambiguous it is because there are two fields or properties with the same name in assembly references that are not directly specified in the code.
I am currently working on a topdown game made in windows forms. In the game, your character rotates after your mouse and you can shoot a shot from your character in the direction of your mouse. To create multiple areas in the game, I chose to use groupboxes as separate areas in the game that you can switch between using buttons but I've run in to a problem. I can no longer rotate or move my character or even shoot within the groupboxes.
I've tried setting breakpoints and discovered that the keyup, keydown and mousemove methods are not being called but I don't know why. For some reason I get an error when i release space in the btnSave_Click method which i marked in the code.
static Image originalImage;
bool pRight, pLeft, pUp, pDown;
string[] Saves;
Save[] RSaves = new Save[4];
Save yoursave;
Save temp;
int slot;
NewGame newgame;
SavedGames savedgames;
string savedata, name = "";
int lvl = 1;
double exp = 0, money = 0;
int pSpeed = 5;
double deltaY, deltaX;
float interval = 7;
Point start;
Point nextStart;
Point cursor;
float radian;
const double Rad2Grad = (180 / Math.PI);
public MainGame()
{
InitializeComponent();
pbPlayer.BringToFront();
gbxTown.AllowDrop = true;
gbxQ1.AllowDrop = true;
pbShot.Location = pbPlayer.Location;
// newgame = new NewGame();
// savedgames = new SavedGames();
originalImage = pbPlayer.Image;
}
public void setSaves(string savedata, int slot)
{
Saves = savedata.Split('#');
string a1 = Saves[0];
string a2 = Saves[1];
string a3 = Saves[2];
string a4 = Saves[3];
RSaves[0] = temp.StringToSaves(temp, a1);
RSaves[1] = temp.StringToSaves(temp, a2);
RSaves[2] = temp.StringToSaves(temp, a3);
RSaves[3] = temp.StringToSaves(temp, a4);
yoursave = RSaves[slot - 1];
name = yoursave.getName();
this.slot = slot;
Controls.Add(pbPlayer);
Controls.Add(pbShot);
}
private void MainGame_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.A)
{
pRight = false;
pLeft = true;
}
else if (e.KeyData == Keys.D)
{
pRight = true;
pLeft = false;
}
else if (e.KeyData == Keys.S)
{
pUp = true;
pDown = false;
}
else if (e.KeyData == Keys.W)
{
pUp = false;
pDown = true;
}
if (e.KeyData == Keys.Space)
{
start = pbPlayer.Location;
cursor = Cursor.Position;
nextStart = start;
deltaY = cursor.Y - start.Y;
deltaX = cursor.X - start.X;
double test = Angle(start, cursor);
radian = (float)(Angle(start, cursor) - 175);
timer2.Enabled = true;
}
}
private void MainGame_KeyUp_1(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.A)
{
pLeft = false;
}
else if (e.KeyData == Keys.D)
{
pRight = false;
}
else if (e.KeyData == Keys.S)
{
pUp = false;
}
else if (e.KeyData == Keys.W)
{
pDown = false;
}
if (e.KeyData == Keys.Space)
{
timer2.Stop();
pbShot.Location = start;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
MovePlayer();
//checkCollision();
}
private void btnNextArea_Click(object sender, EventArgs e)
{
pbPlayer.Parent = gbxQ1;
pbShot.Parent = gbxQ1;
gbxQ1.Location = new Point(0, 0);
gbxTown.Location = new Point(605, 0);
pbPlayer.Location = new Point(100, 200);
pbShot.Location = pbPlayer.Location;
}
private void btnSave_Click(object sender, EventArgs e)
{
newgame = new NewGame();
savedgames = new SavedGames();
RSaves[slot - 1] = new Save(name, money, lvl, exp);
for (int i = 0; i < 4; i++) //When the Spacebar is released, a System.IndexOutOfRangeException error happens for i.
{
Saves[i] = RSaves[i].SavesToString();
}
savedata = Saves[0] + Saves[1] + Saves[2] + Saves[3];
System.IO.File.WriteAllLines(#"saves.txt", Saves);
newgame.setSaves(savedata);
savedgames.setSaves(savedata);
}
private void btnBack_Click(object sender, EventArgs e)
{
pbPlayer.Parent = gbxTown;
pbShot.Parent = gbxTown;
gbxTown.Location = new Point(0, 0);
gbxQ1.Location = new Point(605, 0);
pbPlayer.Location = new Point(100, 200);
pbShot.Location = pbPlayer.Location;
}
private void MainGame_MouseMove_1(object sender, MouseEventArgs e)
{
var y2 = e.Y;
var y1 = (this.pbPlayer.Location.Y + (this.pbPlayer.Height / 2));
var x2 = e.X;
var x1 = (this.pbPlayer.Location.X + (this.pbPlayer.Width / 2));
var angle = (float)Math.Atan2((y1 - y2), (x1 - x2));
pbPlayer.Image = RotateImage(originalImage, (angle * 57));
}
private double Angle(Point start, Point end)
{
return (float)Math.Atan2(end.Y - start.Y, end.X - start.X) * 57;
}
private void timer2_Tick_1(object sender, EventArgs e)
{
nextStart.X -= Convert.ToInt16(interval * ((float)Math.Cos(radian / Rad2Grad)));
nextStart.Y -= Convert.ToInt16(interval * ((float)Math.Sin(radian / Rad2Grad)));
pbShot.Location = nextStart;
}
public static Image RotateImage(Image img, float rotationAngle)
{
Bitmap bmp = new Bitmap(img.Width, img.Height);
Graphics gfx = Graphics.FromImage(bmp);
gfx.TranslateTransform((float)bmp.Width / 2, (float)bmp.Height / 2);
gfx.RotateTransform(rotationAngle);
gfx.TranslateTransform(-(float)bmp.Width / 2, -(float)bmp.Height / 2);
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.DrawImage(img, new Point(0, 0));
gfx.Dispose();
return bmp;
}
private void MovePlayer()
{
if (pRight == true && pbPlayer.Left < 900)
{
pbPlayer.Left += pSpeed;
}
else if (pLeft == true && pbPlayer.Left > 0)
{
pbPlayer.Left -= pSpeed;
}
else if (pUp == true && pbPlayer.Top < 600)
{
pbPlayer.Top += pSpeed;
}
else if (pDown == true && pbPlayer.Top > 0)
{
pbPlayer.Top -= pSpeed;
}
}
The expected outcome is for the movement, aiming and firing to work as intended within the groupboxes but currently they do not execute in the code while in the groupboxes. It works fine in the form but not in the groupboxes. I would appriciate any help.
I have a picturebox in windows form application that has the ability to move with arrowkeys. I want it to have certain limits to where it can go, specifically in the form. How do I do this? My class to move the target is below:
namespace AmazingPaintball
{
class Target
{
private Point p;
public Target(Point myPoi)
{
p = myPoi;
}
public Point Move(Keys key)
{
if (key == Keys.Left)
{
p.Offset(-50, 0);
}
else if (key == Keys.Right)
{
p.Offset(50, 0);
}
else if (key == Keys.Up)
{
p.Offset(0, -50);
}
else if (key == Keys.Down)
{
p.Offset(0, 50);
}
return p;
}
}
}
Below is the form1:
namespace AmazingPaintball
{
public partial class Form1 : Form
{
Random positionX = new Random();
Random positionY = new Random();
Target einstein;
int count = 0;
Paintballs pBalls = new Paintballs();
Stopwatch stopwatch = new Stopwatch();
SoundPlayer wavPlayer = new SoundPlayer(#"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\Resources\singlegunshot.wav");
SoundPlayer wavPlayer2 = new SoundPlayer(#"G:\ChefBrohansPaintballFunNew\ChefBrohansPaintballFun\bin\Debug\Resources\Applause.wav");
public Form1()
{
InitializeComponent();
Point point = new Point(positionX.Next(0, 638), positionY.Next(0, 404));
einstein = new Target(point);
ptrEinstein.Location = point;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
pBalls.paint(e.Graphics);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
ptrEinstein.Location = einstein.Move(e.KeyData);
pictureBox1.Update();
pictureBox1.Refresh();
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
wavPlayer.Play();
pBalls.add(e.Location);
pictureBox1.Refresh();
count++;
}
private void Form1_Load(object sender, EventArgs e)
{
stopwatch.Start();
}
private void ptrEinstein_MouseClick(object sender, MouseEventArgs e)
{
count++;
ptrEinstein.Image = Properties.Resources.AlbertEinsteinTongue;
stopwatch.Stop();
wavPlayer2.Play();
MessageBox.Show("It took " + count + " shots and " + stopwatch.Elapsed + " seconds to hit the target");
wavPlayer2.Stop();
ptrEinstein.Image = Properties.Resources.AlbertEinsteinFace;
count = 0;
stopwatch.Reset();
stopwatch.Start();
}
}
}
The picturebox is ptrEinstein and it is able to move in the form1_keydown event.
When you're moving the picture box, first check to make sure where you're moving it to is inside the form. E.g. check if the new X + the width of the picture box is less than the width of the form, etc.
This will be incomplete because we do not have your code, but you should compare the clientSize properties to the picturebox location (taking into account the size of the picturebox):
PictureBox pb = new PictureBox();
int newX = oldX + xOffset; // xOffset is whatever you're incrementing x by
int newY = oldY + yOffset; // yOffset is whatever you're incrementing y by
if (newX < 0) {
newX = 0;
} else if (newX > this.ClientSize.Width - pb.Width) {
newX = this.ClientSize.Width - pb.Width;
}
if (newY < 0) {
newY = 0;
} else if (newY > this.ClientSize.Height - pb.Height) {
newY = this.ClientSize.Height - pb.Height;
}
// New point to move it to
Point newP = new Point(newX, newY);