I can't make a function so that during the movement of the picturebox which happens with a while loop.
I executed a script on certain coordinates, I tried to do it using the switch statement, but the function simply does not work
When you run it, nothing happens, as if this line of code does not exist.
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 shadowfiend_minigame
{
public partial class Form1 : Form
{
private int _first_shadowrazeX = 404, _first_shadowrazeY = 204;
private int _second_shadowrazeX = 724, _second_shadowrazeY = 204;
private int _third_shadowrazeX = 1106, _third_shadowrazeY = 204;
private int zeus_hp = 1000;
private int shadow_fiend_hp = 2800;
Point point = new Point(1106, 204);
Point point2 = new Point(724, 204);
Point point3 = new Point(404, 204);
private int speed_zeus, damage_zeus;
private int shadow_fiend_damage;
Thread thread = new Thread(ShadowRaze_Click);
public Form1()
{
InitializeComponent();
this.KeyDown += new KeyEventHandler(ShadowRaze_Click);
KeyPreview = true;
}
bool CheckedBox()
{
bool checked1 = checkBox1.Checked;
bool checked2 = checkBox2.Checked;
bool checked3 = checkBox3.Checked;
if (checked1 == false && checked2 == false && checked3 == false)
{
return false;
}
else return true;
}
private async void Start_Click(object sender, EventArgs e)
{
Thread thread = new Thread(Zeus);
if (CheckedBox() == false)
{
MessageBox.Show("Выберите сложность игры!");
}
else
{
Start.Visible = false;
checkBox1.Visible = false;
checkBox2.Visible = false;
checkBox3.Visible = false;
thread.Start();
}
}
private async void Zeus()
{
Thread thread = new Thread(Zeus);
while (shadow_fiend_hp != 0)
{
for (int i = 0; i < 50; i++)
{
var x = _zeus.Location.X;
this.Invoke(new Action(() => _zeus.Location = new Point(_zeus.Location.X - 20, _zeus.Location.Y)));
Thread.Sleep(speed_zeus);
switch (_zeus.Location.X)
/*
* Here it is necessary that when the picturebox reaches a certain point while moving, the function is executed
*/
{
case 1106:
zeus_hp = zeus_hp - 200;
this.Invoke(new Action(() => label4.Text = "zeus_hp: " + zeus_hp));
break;
case 724:
zeus_hp = zeus_hp - 200;
this.Invoke(new Action(() => label4.Text = "zeus_hp: " + zeus_hp));
break;
case 404:
zeus_hp = zeus_hp - 200;
this.Invoke(new Action(() => label4.Text = "zeus_hp: " + zeus_hp));
break;
}
}
Zeus_Attack(damage_zeus);
if (shadow_fiend_hp == 0)
{
MessageBox.Show("You lose");
this.Invoke(new Action(() => Start.Visible = true));
this.Invoke(new Action(() => checkBox1.Visible = true));
this.Invoke(new Action(() => checkBox2.Visible = true));
this.Invoke(new Action(() => checkBox3.Visible = true));
}
else if (zeus_hp == 0)
{
MessageBox.Show("You win");
this.Invoke(new Action(() => Start.Visible = true));
this.Invoke(new Action(() => checkBox1.Visible = true));
this.Invoke(new Action(() => checkBox2.Visible = true));
this.Invoke(new Action(() => checkBox3.Visible = true));
}
for (int i = 0; i < 50; i++)
{
this.Invoke(new Action(() => _zeus.Location = new Point(_zeus.Location.X + 20, _zeus.Location.Y)));
Thread.Sleep(speed_zeus);
}
}
thread.Join();
ResetAll();
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
checkBox3.Checked = false;
checkBox1.Checked = false;
speed_zeus = 30;
damage_zeus = 200;
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
checkBox1.Checked = false;
checkBox2.Checked = false;
speed_zeus = 10;
damage_zeus = 400;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
checkBox3.Checked = false;
checkBox2.Checked = false;
speed_zeus = 50;
damage_zeus = 100;
}
private async void Zeus_Attack(int damage)
{
shadow_fiend_hp = shadow_fiend_hp - damage;
this.Invoke(new Action(() => hp.Text = "HP: " + shadow_fiend_hp));
}
private async void ShadowFiend_Attack()
{
zeus_hp = zeus_hp - 200;
this.Invoke(new Action(() => label4.Text = "HP: " + shadow_fiend_hp));
}
private void ResetAll()
=> this.Invoke(new Action(() => hp.Text = "HP: 2800"));
private async void ShadowRaze_Click(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Z:
shock.Location = new Point(_first_shadowrazeX, _first_shadowrazeY);
shock.Visible = true;
this.Update();
Thread.Sleep(100);
shock.Visible = false;
break;
case Keys.X:
shock.Location = new Point(_second_shadowrazeX, _second_shadowrazeY);
shock.Visible = true;
this.Update();
Thread.Sleep(100);
shock.Visible = false;
break;
case Keys.C:
shock.Location = new Point(_third_shadowrazeX, _third_shadowrazeY);
shock.Visible = true;
this.Update();
Thread.Sleep(100);
shock.Visible = false;
break;
}
}
}
}
Here's some pretty simple code to move a picture box around the screen using async and await. It's not based on your code - yours is far from being a Minimal Reproduceable Example. This is.
I dropped a few coptrols my form:
A combo box
Two textboxes (Offset and Period)
Two Buttons (Go and Stop)
A PictureBox (I made this public and gave it an obvious background color
Then I created this enum to state the direction I wanted to move the picture box:
public enum Direction
{
SouthEast,
East,
NorthEast,
North,
NorthWest,
West,
SouthWest,
South,
}
Then I created this worker class:
internal class PictureBoxMover
{
public bool enabled = true;
Direction _direction;
int _offset;
int _period;
Form1 _theForm;
private static Dictionary<Direction, (int deltaX, int deltaY)> _deltaRules = new Dictionary<Direction, (int deltaX, int deltaY)> {
{ Direction.North, (0, -1) },
{ Direction.South, (0, 1) },
{ Direction.East, (1, 0) },
{ Direction.West, (-1, 0) },
{ Direction.NorthEast, (1, -1) },
{ Direction.NorthWest, (-1, -1) },
{ Direction.SouthEast, (1, 1) },
{ Direction.SouthWest, (-1, 1) },
};
public PictureBoxMover (Form1 parentForm, Direction direction, int offset, int period)
{
_theForm = parentForm;
_direction=direction;
_offset=offset;
_period=period;
}
public void Disable()
{
enabled = false;
}
public async Task Run()
{
var directionRule = _deltaRules[_direction];
var offsetXY = (directionRule.deltaX * _offset, directionRule.deltaY * _offset);
while (enabled)
{
_theForm.pictureBox1.Location = new Point(_theForm.pictureBox1.Location.X + offsetXY.Item1, _theForm.pictureBox1.Location.Y + offsetXY.Item2);
await Task.Delay(_period);
}
}
}
The static _deltaRules dictionary makes sense of the Directions. The ( 1, -1 ) denotes a tuple of two integers (i.e., _deltaRules is a dictionary with a Direction as key and a two integer tuple as value
The main reason for instance of this class is to allow them to be easily cancellable (/disablable).
In the form's constructor, I bind the Direction dropdown combobox to the possible values of Direction:
DirectionDropDown.DataSource = Enum.GetNames<Direction>();
The rest of the form's class looks like this:
private PictureBoxMover? _currentPictureBoxMover = null;
private async void GoBtn_Click(object sender, EventArgs e)
{
if (Enum.TryParse<Direction>(DirectionDropDown.SelectedItem.ToString(), out var direction) &&
int.TryParse(OffsetTxt.Text, out var offset) &&
int.TryParse(PeriodTxt.Text, out var period))
{
if (_currentPictureBoxMover != null)
{
_currentPictureBoxMover.Disable();
}
_currentPictureBoxMover = new PictureBoxMover(this, direction, offset, period);
await _currentPictureBoxMover.Run();
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
if (_currentPictureBoxMover != null)
{
_currentPictureBoxMover.Disable();
}
_currentPictureBoxMover = null;
}
I keep track of the _currentPictureBoxMover so that I can disable it when I start moving in a new direction. Otherwise the code is pretty self-explanatory.
Note that because everything is done with async and await, I have no threading issues, and no timers to worry about.
One thing to note: part of the reason for having the period/offset controls is to show (and prove to myself) that the form is fully functional while things are moving around
I have background worker where I am getting some callback in a thread and I am updating the UI and the progress bar as the states change. Currently there are 3 states 1) Cartridgr Drawer Closed 2) Processing 3) Processed.
First Time when the application starts everything works fine. The Run Worker Completed fires after the Processed state and I am launching an other success window through an event.
But for the second when I rerun the workflow without closing the application, I get the success Window when the worker still says Processing. Why is that also the remaining time that I am updating behaves incorrectly. Please help. (Please see the DoWork event Thread th I guess thats the issue).
//This method is a RelayCommand thats called on some button click
private void StartCurrentRun(bool obj)
{
this.worker = new BackgroundWorker();
this.worker.WorkerReportsProgress = true;
this.worker.WorkerSupportsCancellation = true;
StartTimer();
PropertyCallBackChangedInstance.PropertyChanged -= PropertyCallBackChangedInstance_PropertyChanged;
WhenCancelledBlurVolumesGrid = false;
this.worker.DoWork += this.DoWork;
this.worker.ProgressChanged += this.ProgressChanged;
this.worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
IsLiveProgress = true;
this.worker.RunWorkerAsync();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
int OriginalTimeRemaining = SelectedVolumeEstimatedTime();
int TotalPrecentagebasedOnNumberOfStates = 50;
int PercentProgress = 100 / TotalPrecentagebasedOnNumberOfStates;
CurrentCartridgeStatus status = CurrentCartridgeStatus.NotProcessed;
var instance = ConnectToInstrument.InstrumentConnectionInstance;
instance.InitalizeRun();
Thread th = new Thread(() =>
{
PropertyCallBackChangedInstance.PropertyChanged += PropertyCallBackChangedInstance_PropertyChanged;
});
th.Start();
Thread th2 = new Thread(() =>
{
while (PropertyCallBackChangedInstance.CurrentCartridgeStatusChanged != CurrentCartridgeStatus.Processed)
{
lock (_objectForThread2)
{
if (OriginalTimeRemaining > 0)
{
OriginalTimeRemaining -= 2;
}
var time = TimeSpan.FromSeconds(OriginalTimeRemaining);
EstimatedTimeRemaining = string.Format("{0:00}:{1:00}:{2:00}",
time.Hours,
time.Minutes,
time.Seconds);
OnPropertyChanged("EstimatedTimeRemaining");
}
Thread.Sleep(2000);
}
});
th2.Start();
int counter = 0;
for (int i = 0; i < PercentProgress; i++)
{
//Keep checking to see if the Run is cancelled
if (WhenCancelledBlurVolumesGrid) //That means the run is cancelled
{
if (worker.CancellationPending)
{
e.Cancel = true;
worker.CancelAsync();
}
}
for (int j = counter; j <= TotalPrecentagebasedOnNumberOfStates; j++)
{
worker.ReportProgress(Math.Min(j, 100));
if (status != CurrentCartridgeStatus.Processed)
{
Thread.Sleep(55);
}
}
counter = 50;
TotalPrecentagebasedOnNumberOfStates += 50;
}
th.Join();
th2.Join();
}
private void PropertyCallBackChangedInstance_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "CurrentCartridgeStatusChanged")
{
var value = sender as InstrumentCallBackProperties;
CurrentStatus = EnumExtensions.GetDescription(value.CurrentCartridgeStatusChanged);
}
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.ProgressValue = e.ProgressPercentage;
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
EstimatedTimeRemaining = "00:00:00";
stopWatch.Stop();
timer.Stop();
Messenger.Default.Send(new NotificationMessage("RunComplete"));
if (e.Cancelled)
{
SelectedVolume = string.Empty;
}
else
{
IsLiveProgress = false;
if (IsRunSuccessfullyComplete != null && !WhenCancelledBlurVolumesGrid) //This indicates that Success will only open when the run is complete
{
IsRunSuccessfullyComplete(NoErrors);//This event opens the success window from a different page
}
WhenCancelledBlurVolumesGrid = true;
}
//I have some Dispose method that i am trying to do after the first run.
public void Dispose()
{
if (this.worker != null)
{
this.ProgressValue = 0;
this.worker.CancelAsync();
this.worker.Dispose();
this.worker = null;
timer = null;
stopWatch = null;
TimeElapsed = string.Empty;
}
}
I'm making a memory game and i need to set a timer to reset de images if they don't match but it doesn't work to turn the pictures back to hidden:
//set images
if (clickedLabel != null)
{
var Index = Convert.ToInt32(clickedLabel.Tag);
clickedLabel.Image = icons[Index];
//Check first clicked
if (firstClicked == null)
{
firstClicked = clickedLabel;
return;
}
secondClicked = clickedLabel;
timer1.Start();
}
Method timer1_Tick:
//Timer
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
firstClicked = null;
secondClicked = null;
}
This might work :
class YourClass
{
System.Timers.Timer aTimer;
void YourMethod()
{
//code
if (clickedLabel != null)
{
var Index = Convert.ToInt32(clickedLabel.Tag);
clickedLabel.Image = icons[Index];
//Check first clicked
if (firstClicked == null)
{
firstClicked = clickedLabel;
return;
}
secondClicked = clickedLabel;
SetTimer();
}
private static void SetTimer ()
{
//System.Timers.Timer aTimer; at the beginning of your class
aTimer = new System.Timers.Timer (2000); //the time you want in milliseconds
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = false;
aTimer.Enabled = true;
}
}
The AutoReset set to false will make the Elapsed event trigger only once. Then, you do what you want in that event.
private static void OnTimedEvent (Object source, ElapsedEventArgs e)
{
firstClicked = null;
secondClicked = null;
}
You might want to use Stop and Dispose methods on aTimer when you don't need it anymore.
You also should be more specific when posting questions, to be sure to have the help you need :)
I want to do frame animation and not sure should i use AnimationDrawable class for animation.
How do frame animation in Xamarin forms for Android. Is there any other approach? Simple example would be perfect.
I did trick just hiding and unhiding required elements. You could call from DoAnimation from any button click or smth else.
private void DoAnimation()
{
_timer = new System.Timers.Timer();
//Trigger event every second
_timer.Interval = 1000;
_timer.Elapsed += CheckStatus;
//count down 5 seconds
_countSeconds = 5000;
_timer.Enabled = true;
}
private void SpinAnimation()
{
switch (_letterShowState) {
case SomeStateStates.State1:
_pic1.IsVisible = false;
_pic2.IsVisible = true;
_pic3.IsVisible = false;
_letterShowState = SomeStateStates.State2;
break;
}
}
private void CheckStatus(object sender, System.Timers.ElapsedEventArgs e) {
_countSeconds--;
new System.Threading.Thread(new System.Threading.ThreadStart(() => {
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => {
SpinAnimation();
});
})).Start();
if (_countSeconds == 0)
{
_timer.Stop();
}
}
I check a condition on my form_load event whether the form window should be closed or not. If so, a timer with an interval of 3000 will be started and after the tick, the form should be closed. When I check my debugger, even though the condition returns true, the debugger jumps over my timer.Start() method and my timer is never ticked.
I have defined the timer in my class as System.Windows.Forms.Timer timer; and this is how I am initiating it:
timer = new System.Windows.Forms.Timer();
this.timer.Enabled = true;
this.timer.Interval = 3000;
this.timer.Tick += new System.EventHandler(this.timer_Tick_1);
The tick event:
private void timer_Tick_1(object sender, EventArgs e)
{
this.Close();
}
And the condition is as simple as:
if (closeWindow)
timer.Start();
And trust me, the closeWindow returns true.
P.s. Strangely enough, this timer used to work. I know I have it messed up somewhere perhaps. But I do not know where.
Update: the form_load event
private void FormMain_Load(object sender, EventArgs e)
{
metroLabelBuild.Text = args["name"] + " " + args["action"];
if (CheckArguments(args, 18))
{
try
{
campaignRecipientsFileLocation = args["recipientsfile"].Trim();
campaignName = args["name"].Trim();
campaignDescription = args["description"].Trim();
campaignAction = args["action"].Trim();
campaignOutputFormat = args["outputformat"].Trim();
campaignType = args["type"].Trim().ToLower();
campaignDelimiter = args["delimeter"].Trim();
campaignOutputPath = args["outputpath"].Trim();
campaignFileName = args["filename"].Trim();
campaignId = Convert.ToInt64(args["id"].Trim());
campaignFixedCost = Convert.ToInt32(args["fixedcost"]);
campaignVariableCost = Convert.ToInt32(args["variablecost"]);
campaignControlGroup = Convert.ToInt32(args["controlgroup"]);
campaignFtpId = Convert.ToInt64(args["ftpid"].Trim());
campaignHasSpyList = (args["hasspylist"].ToLower().Equals("true") || args["hasspylist"].Equals("1")) ? true : false;
closeWindow = (args["closewindow"].ToLower().Equals("true") || args["closewindow"].Equals("1")) ? true : false;
campaignShouldUploadToFTP = (args["shoulduploadtoftp"].ToLower().Equals("true") || args["shoulduploadtoftp"].Equals("1")) ? true : false;
}
catch
{
listBoxMessages.Items.Add("Error preparing the arguments.");
continueProcess = false;
this.Close();
}
finally
{
logger = new Logger(loggerEnabled, cs);
fh = new FileHelper(logger);
rh = new RecipientHelper(logger);
dbh = new DatabaseHelper(logger, cs);
if (continueProcess)
{
InsertCampaignRun("Running");
RunCampaign();
if (closeWindow)
timer.Start();
}
}
}
else
{
if (closeWindow)
timer.Start();
}
}