WPF- Why keyDown function in my project does not work? - c#

I want to add to this game: https://www.mooict.com/wpf-c-tutorial-create-a-fun-balloon-popping-game-in-visual-studio/
A function ColorKeyIsDown() that is activated when some of keys: Y,R,B,G,O are pressed.
So, if any of these keys is pressed, a specific balloon will be removed from the canvas.
I made 5 possible tags for every newBalloon that is made,
because ballonSkins integer value is from 1-5, every number declares a different background of the newBallon.
In ColorKeyIsDown() I want to identify the balloons by their tags,
But it does not work.
How can I identify each different balloon(yellow/red/blue balloon)?
Can I identify the balloon by it's background?
*In XAML:
<Canvas Name="MyCanvas" Focusable="True" MouseLeftButtonDown="popBalloons" Background="White" KeyDown="ColorKeyIsDown">
<Label Name="scoreLabel" FontSize="24" Content="Score: 0" Foreground="black" FontWeight="ExtraBold" Canvas.Top="527" />
</Canvas>
*In C# Code:
private void ColorKeyIsDown(object sender, KeyEventArgs e)
{
if (gameisactive)
{
foreach(var x in MyCanvas.Children.OfType<Rectangle>())
{
switch (e.Key)
{
case Key.Y:
if ((string)x.Tag == 3.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
case Key.R:
if ((string)x.Tag == 1.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
case Key.B:
if ((string)x.Tag == 5.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
case Key.G:
if ((string)x.Tag == 4.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
case Key.O:
if ((string)x.Tag == 2.ToString()) { MyCanvas.Children.Remove(x); score++; }
break;
}
}
}
}
*In C#- in gameEngine() function:
// check which skin number is selected and change them to that number
switch (balloonSkins)
{
case 1:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon1.png"));
break;
case 2:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon2.png"));
break;
case 3:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon3.png"));
break;
case 4:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon4.png"));
break;
case 5:
balloonImage.ImageSource = new BitmapImage(new Uri("pack://application:,,,/files/balloon5.png"));
break;
}
// make a new rectangle called new balloon
// inside this it has a tag called bloon, height 70 pixels and width 50 pixels and balloon image as the background
Rectangle newBalloon = new Rectangle
{
Tag = balloonSkins.ToString(),
Height = 70,
Width = 50,
Fill=balloonImage
};

Someone wrote that instead of doing the KeyDown event in Canvas,
to do it in the window browser. solution: onkeydown event not working on canvas?
*I changed it, and it works!

Related

Detecting when the user is pressing the shift key

Currently I am working on a Piano in Windows Form Application. What I did is when you press a certain key on the keyboard it plays a sound (technically it force a press of button). Now what I want to do is add that when the user is pressing a key as well as pressing the shift key, it will play a longer sound. For example if the A key is pressed it will play sound of the C chord, and if the A is pressed + the shift key is pressed it will play a longer version of the sound. This is the code for the key pressing and an example of one of the sounds playing:
private bool shiftPressed = false;
const int NOTE_LENGTH = 500;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.A://C
C_Low.BackColor = Color.Gray;
C_Low.PerformClick();
break;
case Keys.S://D
D_Low.BackColor = Color.Gray;
D_Low.PerformClick();
break;
case Keys.D://E
E_Low.BackColor = Color.Gray;
E_Low.PerformClick();
break;
case Keys.F://F
F_Low.BackColor = Color.Gray;
F_Low.PerformClick();
break;
case Keys.G://F
G_Low.BackColor = Color.Gray;
G_Low.PerformClick();
break;
case Keys.H://A
A_Low.BackColor = Color.Gray;
A_Low.PerformClick();
break;
case Keys.J://B
B_Low.BackColor = Color.Gray;
B_Low.PerformClick();
break;
case Keys.W://C#
C_Diez_Low.BackColor = Color.Gray;
C_Diez_Low.PerformClick();
break;
case Keys.E://D#
D_Diez_Low.BackColor = Color.Gray;
D_Diez_Low.PerformClick();
break;
case Keys.T://F#
F_Diez_Low.BackColor = Color.Gray;
F_Diez_Low.PerformClick();
break;
case Keys.Y://G#
G_Diez_Low.BackColor = Color.Gray;
G_Diez_Low.PerformClick();
break;
case Keys.U://A#
A_Diez_Low.BackColor = Color.Gray;
A_Diez_Low.PerformClick();
break;
}
return base.ProcessCmdKey(ref msg, keyData);
}
As example the C_Low_Click_1 event:
private void C_Low_Click_1(object sender, EventArgs e) //Play C low
{
if (shiftPressed)
{
C_Low.BackColor = Color.White;
if (Low.Checked)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.C_Low_Long);
player.Load();
player.PlaySync();
}
if (Med.Checked)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.C_Medium_Long);
player.Load();
player.PlaySync();
}
if (High.Checked)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.C_High_Long);
player.Load();
player.PlaySync();
}
}
else
{
C_Low.BackColor = Color.White;
if (Low.Checked)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.C_Low);
player.Load();
player.PlaySync();
}
if (Med.Checked)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.C_Medium);
player.Load();
player.PlaySync();
}
if (High.Checked)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.C_High);
player.Load();
player.PlaySync();
}
}
}
Any help will be appreciated, and if I did not provide any information please tell me :D
You should consider to use the KeyEvents of your form, especially the KeyDown and KeyUp events. Important: to use the event properly, you must set the KeyPreview attribute to true first!
Then use following code within the KeyDown event:
shiftPressed = e.Shift;
and in the KeyUp event:
shiftPressed = false;
// also possible, although I won't recommend using the code below,
// as there could be some incorrect handling if shift is pressed
// shiftPressed = e.Shift;
Keys is a flags enum, so you would test for the shift key using:
var shiftPressed = keyData.HasFlag(Keys.Shift);
When shift is pressed your switch statement won't work (as the value isn't Keys.A, for example, it's Keys.Shift|Keys.A). You can remove the shift first so your switch statement will work:
var keyWithoutShift = keyData & ~Keys.Shift;
switch (keyWithoutShift)
{
// handle keys as normal
}

How do I set timer to making an on off button for 1000 milliseconds?

I am new to c# and I'm wanting to create a game that it has three button with different colors , I want to turn on and off each of them in random state for 1000 milisecond .. what should I do ? can anyone help me ? :)
there are three buttons including Red , Blue and Green colors , after click the "start" button they begin to blink randomly ... I want set 1000 millisecond for this blink !
switch (colorNum)
{
case 1:
btnRed.BackColor = Color.Red;
Thread.Sleep(milisecond);
//if (btn == btnRed)
//{
count++;
break;
//}
case 2:
btnBlue.BackColor = Color.Blue;
//{
count++;
break;
//}
case 3:
btnYellow.BackColor = Color.Yellow;
//{
count++;
break;
//}
}
private void Blink_Button()
{
Random rnd = new Random();
int colorNum = rnd.Next(1, 4);
switch (colorNum)
{
case 1:
btnRed.BackColor = Color.Red;
btnBlue.BackColor = Color.LightGray;
btnYellow.BackColor = Color.LightGray;
break;
case 2:
btnBlue.BackColor = Color.Blue;
btnRed.BackColor = Color.LightGray;
btnYellow.BackColor = Color.LightGray;
break;
case 3:
btnYellow.BackColor = Color.Yellow;
btnRed.BackColor = Color.LightGray;
btnBlue.BackColor = Color.LightGray;
break;
}
}
Call this method in the Timer tick event

Program skipping stages

So I have a Unity program, where it switches screens if the user presses ENTER.
However, whenever the user presses enter, instead of just going one screen forward, it skips all the way to the last screen.
Here is my OnGUI():
if (showScreen == true)
{
//this allows the screens to toggle
switch (pageNum)
{
case 1:
rectangle = GUI.Window(1,rectangle, Page1, "Computer");
break;
case 2:
rectangle = GUI.Window(1,rectangle, Page2, "Computer");
break;
case 3:
rectangle = GUI.Window(1,rectangle, Page3, "Computer");
break;
case 4:
rectangle = GUI.Window(1,rectangle, Page4, "Computer");
break;
case 5:
rectangle = GUI.Window(1,rectangle, Page5, "Computer");
GUILayout.Window (2,rect2, popUp, "Warning!");
break;
case 6:
rectangle = GUI.Window(1,rectangle, Page6, "Computer");
break;
case 7:
rectangle = GUILayout.Window(1,rectangle, Page7, "Computer");
break;
default:
break;
}
}
And here is where the GUIs are actually set up, and made to change:
void Page1(int windowID)
{ if (Input.GetKeyDown(KeyCode.Return))
{
GUI.FocusControl(null);
pageNum = 2;
}
}
void Page2(int windowID)
{
if (Input.GetKeyDown(KeyCode.Return))
{
pageNum = 3;
GUI.FocusControl(null);
}
}
//continue like this for 5 more Page#(int windowID)
So what can I insert into these classes to make my program stop skipping? should I put a pause into these if statements too?
So it looks like the easiest way to solve this problem is by changing how the program changes the stages. All you need to do is a boolean that changes to true once the return key has been pressed.
so just declare the boolean:
public class ClassName : MonoBehaviour
{
bool wasClicked = false;
Then to change the states just do this:
if (Input.GetKey(KeyCode.Return))
{
wasClicked = true;
}
if (wasClicked)
{
if (!Input.GetKey(KeyCode.Return))
{
GUI.FocusControl(null);
pageNum = next page number;
wasClicked = false;
}
}

Dynamic random call to image elements to XAML from C#

I have the following code in C#. A function by which I want to highlight one of the nine images at random. The code is as follows,
public void randomize(object sender, MouseButtonEventArgs e)
{
String img = "image";
int random = RandomNumber(10, 18); //Generate Random Number
score.Content = random;
img += random; //append generated number to "image"
//Call function to highlight behind image
ToGold(random);
}
I tried to make the function call ToGold(random) to be able to dynamically refer to one of the images on XAML. But I was not able to make the code work as I intended. So I took a brute force approach as below,
public void ToGold(int Img)
{
Uri gold = new Uri("/Start;component/Images/gold1.png", UriKind.Relative); //Set Uri path of gold image
ImageSource ImgSrc = new BitmapImage(gold); //Define ImageSource and assign
switch(Img)
{
case 10:
{
image10.Source = ImgSrc;
break;
}
case 11:
{
image11.Source = ImgSrc;
break;
}
case 12:
{
image12.Source = ImgSrc;
break;
}
case 13:
{
image13.Source = ImgSrc;
break;
}
case 14:
{
image14.Source = ImgSrc;
break;
}
case 15:
{
image15.Source = ImgSrc;
break;
}
case 16:
{
image16.Source = ImgSrc;
break;
}
case 17:
{
image17.Source = ImgSrc;
break;
}
case 18:
{
image18.Source = ImgSrc;
break;
}
}
}
So my question is how do I make the code efficient by making it dynamic? Can anyone please help me?
NOTE: I have just started studying WPF. So please bear with me.
You can use the FindName method on the window to find an element by its name.
Or you could create an array containing your images in order, i.e. { image0, image1, image2, image3, ... } and then access that array with a random index.

how can i apply different color to datapoint of ms chart?

I am working on MS chart, not having so much idea.
I have bind the chart, my next thing is to give different colors of each datapoint?
How can i do that?
My sample code is:
foreach (DataPoint pt in ChartRTM.Series["SeriesSeverity"].Points)
{
string sev = pt.YValues[1].ToString(); // this will be your value depending upon which you could set the color
switch (sev)
{
case "I":
pt.Color = Color.Red;
break;
default:
pt.Color = Color.Blue;
break;
}
}
I think you want to change the Marker color of the point :
To do this, change the switch statement :
switch (sev)
{
case "I":
pt.MarkerColor = Color.Red;
break;
default:
pt.MarkerColor = Color.Blue;
break;
}

Categories