NullExceptionError when trying to load image from Resources - c#

I have my resources embedded in the system, the string I search for them with matches the name of the image yet I still get a ArgumentNullException... How come?
//Check if currencies are chosen
private void Action()
{
label1.Text = null;
//Checks if items are selected then what currencies are chosen
if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1)
{
label1.Text = "Please select currencies";
}
else
{
LB1 = listBox1.SelectedItem.ToString();
LB2 = listBox2.SelectedItem.ToString();
Conversion();
}
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image;
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image;
}
Picture of Resource images
Thank you so much in advance!

You've got a small logic flaw. You are setting variables inside an if condition but using them outside, even if the if condition doesn't execute.
if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1)
{
label1.Text = "Please select currencies";
}
else
{
LB1 = listBox1.SelectedItem.ToString(); //Doesn't always run
LB2 = listBox2.SelectedItem.ToString();
Conversion();
}
//Always runs
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image;
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image;
You should probably change it to something more like this:
if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1)
{
label1.Text = "Please select currencies";
}
else
{
LB1 = listBox1.SelectedItem.ToString();
LB2 = listBox2.SelectedItem.ToString();
Conversion();
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image;
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image; }
}
Or better yet, use a guard, and use local variables, so that the compiler will catch this sort of flaw in the future:
if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1)
{
label1.Text = "Please select currencies";
return;
}
var lb1 = listBox1.SelectedItem.ToString();
var lb2 = listBox2.SelectedItem.ToString();
Conversion(lb1, lb2);
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(lb2) as Image;
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(lb2) as Image;

Related

How to check if image moved by finger? (Manipulation)

I already working with manipulations over images on canvas. Now, I need to check, if image moved on canvas using fingers. How to do this?
void Window_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
{
Image photoToMove = e.OriginalSource as Image;
int photoIndex = photos.IndexOf(photoToMove);
System.Windows.Media.Matrix rectsMatrix = ((MatrixTransform)photoToMove.RenderTransform).Matrix;
rectsMatrix.RotateAt(e.DeltaManipulation.Rotation,
e.ManipulationOrigin.X,
e.ManipulationOrigin.Y);
rectsMatrix.ScaleAt(e.DeltaManipulation.Scale.X,
e.DeltaManipulation.Scale.X,
e.ManipulationOrigin.X,
e.ManipulationOrigin.Y);
rectsMatrix.Translate(e.DeltaManipulation.Translation.X,
e.DeltaManipulation.Translation.Y);
MatrixTransform newImageMTransform = new MatrixTransform(rectsMatrix);
photoToMove.RenderTransform = newImageMTransform;
Rect containingRect =
new Rect(((FrameworkElement)e.ManipulationContainer).RenderSize);
Rect shapeBounds =
photoToMove.RenderTransform.TransformBounds(
new Rect(photoToMove.RenderSize));
if (e.IsInertial && !containingRect.Contains(shapeBounds))
{
e.Complete();
}
if (e.DeltaManipulation.Translation.X > 0 || e.DeltaManipulation.Translation.Y > 0)
{
imageMoved = true;
}
else
{
imageMoved = false;
}
e.Handled = true;
}
At now, this code always says me "imageMoved == true".

How to make two pictures not visible after a certain time

I'm making a memotest and I need to press two different images and they need to keep visible for 3-5 seconds. I've tried Thread.Sleep(5000) but it doesn't show me the second one. What should I do?
The only way I've founded to see for some seconds the images was by putting a MessageBox but that isn't the idea and I don't know other way to do it.
if (pic != null && pic.Name == fondos[i].Name)
{
if (CantClick == 0)
{
ParejaActual = listRandom[i].pareja;
CantClick = 1;
primerI = i;
picAnterior = pic;
imgAnterior = img;
pic.Visible = false;
}
else if (CantClick == 1)
{
pic.Visible = false;
if (ParejaActual == listRandom[i].pareja)
{
SoundPlayer simpleSound = (new SoundPlayer(Configuracion.RootFolder + "aplau.wav"));
simpleSound.Play();
Ganando++;
label3.Text = Ganando.ToString();
//MessageBox.Show("Si");
//NO SE DESTAPA LA SEGUNDA.
//Thread.Sleep(5000);
CantClick = 0;
img.Visible = false;
imgAnterior.Visible = false;
Application.DoEvents();
}
else
{
(new SoundPlayer(Configuracion.RootFolder + "sad.wav")).Play();
MessageBox.Show("No");
Mal++;
CantClick = 0;
label4.Text = Mal.ToString();
pic.Visible = true;
picAnterior.Visible = true;
}
}
}
Thank you!
Instead of using Thread.Sleep , use System.Timers class. After an interval, just hide one image and show the other. Tell me if you want any other help.

Leap Motion gets confused between different gesture types. How to optimize?

The swipe gestures Left,Right, Up and Down are not optimized. If a task has to be performed with an upward swipe, it would get confused with a left swipe and still perform it.Please suggest me the parameters to be optimized for differentiating swipes.Or commands for perfect swipe recognition
Also it gets confused with a circle and a swipe.
I have added my code. In one single frame only one gesture should be detected.How do i limit this here.
public MainWindow()
{
InitializeComponent();
this.controller = new Controller();
this.listener = new LeapListener(this);
controller.AddListener(listener);
for (int iCount = 1; iCount < 23; iCount++)
{
images[iCount] = new BitmapImage();
images[iCount].BeginInit();
images[iCount].UriSource = new Uri("Images/" + iCount + ".png", UriKind.Relative);
images[iCount].EndInit();
}
image.Source = images[1];
}
delegate void LeapEventDelegate(string EventName);
public void LeapEventNotification(string EventName)
{
if (this.CheckAccess())
{
switch (EventName)
{
case "onInit":
break;
case "onConnect":
this.connectHandler();
break;
case "onFrame":
this.checkGestures(this.controller.Frame());
break;
}
}
else
{
Dispatcher.Invoke(new LeapEventDelegate(LeapEventNotification
), new object[] { EventName });
}
}
public void connectHandler()
{
controller.EnableGesture(Gesture.GestureType.TYPE_SWIPE);
this.controller.EnableGesture(Gesture.GestureType.TYPE_CIRCLE);
this.controller.EnableGesture(Gesture.GestureType.TYPE_KEY_TAP);
this.controller.EnableGesture(Gesture.GestureType.TYPE_SCREEN_TAP);
// controller.Config.SetFloat("Gesture.Swipe.Speed", 4000.0f);
controller.Config.SetFloat("Gesture.Swipe.MinVelocity", 750f);
controller.Config.SetFloat("Gesture.Swipe.MinLength", 200f);
controller.Config.SetFloat("Gesture.KeyTap.MinDownVelocity", 40.0f);
controller.Config.SetFloat("Gesture.KeyTap.HistorySeconds", .2f);
controller.Config.SetFloat("Gesture.KeyTap.MinDistance", 40.0f);
controller.Config.SetFloat("Gesture.Circle.MinRadius", 15.0f);
controller.Config.SetFloat("Gesture.Circle.MinArc", 15f);
controller.Config.SetFloat("InteractionBox.Width", 1600.0f);
controller.Config.SetFloat("InteractionBox.Height", 1600.0f);
controller.Config.Save();
}
public void checkGestures(Frame frame)
{
GestureList gestures = frame.Gestures();
foreach (Gesture gesture in gestures)
{
// For Image 1
if (image.Source.Equals(images[1]))
{
if (gesture.Type == Gesture.GestureType.TYPE_SWIPE)
{
SwipeGesture swipe = new SwipeGesture(gesture);
if (swipe.State == Gesture.GestureState.STATE_START && swipe.Direction.x > 0 && Math.Abs(swipe.Direction.y) < 5)
{
image.Source = images[2];
// Console.WriteLine("Second");
}
}
}
// For Image 2
else if (image.Source.Equals(images[2]))
{
if (gesture.Type == Gesture.GestureType.TYPE_SWIPE)
{
SwipeGesture swipe = new SwipeGesture(gesture);
if (swipe.State == Gesture.GestureState.STATE_START && swipe.Direction.y > 0)
{
image.Source = images[3];
}
else if (swipe.State == Gesture.GestureState.STATE_START && swipe.Direction.x > 0 && Math.Abs(swipe.Direction.y) < 5)
{
image.Source = images[7];
}
}
if (gesture.Type == Gesture.GestureType.TYPE_KEY_TAP)
{
KeyTapGesture TapGesture = new KeyTapGesture(gesture);
image.Source = images[1];
Console.WriteLine("Circle");
}
}
// For Image 3
else if (image.Source.Equals(images[3]))
{
if (gesture.Type == Gesture.GestureType.TYPE_SWIPE)
{
SwipeGesture swipe = new SwipeGesture(gesture);
if (swipe.State == Gesture.GestureState.STATE_START && swipe.Direction.y < 0)
{
image.Source = images[4];
}
else if (swipe.State == Gesture.GestureState.STATE_START && swipe.Direction.x < 0 && Math.Abs(swipe.Direction.y) < 5)
{
image.Source = images[16];
}
}
if (gesture.Type == Gesture.GestureType.TYPE_KEY_TAP)
{
KeyTapGesture TapGesture = new KeyTapGesture(gesture);
image.Source = images[1];
}
}
}//foreach
}
}
}
The out of the box Gestures were deprecated in 3.x (Orion) as they weren't to reliable.
The best thing to do is to understand the SDK and just create your own gestures, you can go beyond whats already Out of the box and more reliable.
Everything its about 3d positioning so pay attention to your Y,X,Z, use the debuger hands or create your own debug system to see how it behaves.

Can´t check if array values are true from another class in main class

I am programming a basic writing game in C#. The game will randomly show picture in a picturebox. The pictures is stored in an array in a different class than the main class.
The code to the class looks like this :
public class bildelisteDyr
{
public static Bitmap bildeListe (int index)
{
Bitmap[] bildeListe = new Bitmap[21];
bildeListe[0] = Properties.Resources.ål;
bildeListe[1] = Properties.Resources.ant;
bildeListe[2] = Properties.Resources.bird;
bildeListe[3] = Properties.Resources.bear;
bildeListe[4] = Properties.Resources.butterfly;
bildeListe[5] = Properties.Resources.cat;
bildeListe[6] = Properties.Resources.chicken;
bildeListe[7] = Properties.Resources.dog;
bildeListe[8] = Properties.Resources.elephant;
bildeListe[9] = Properties.Resources.fish;
bildeListe[10] = Properties.Resources.goat;
bildeListe[11] = Properties.Resources.horse;
bildeListe[12] = Properties.Resources.ladybug;
bildeListe[13] = Properties.Resources.lion;
bildeListe[14] = Properties.Resources.moose;
bildeListe[15] = Properties.Resources.polarbear;
bildeListe[16] = Properties.Resources.reke;
bildeListe[17] = Properties.Resources.sheep;
bildeListe[18] = Properties.Resources.snake;
bildeListe[19] = Properties.Resources.spider;
bildeListe[20] = Properties.Resources.turtle;
return bildeListe[index];
}
}
When calling on the values in the array to show picture randomly in the picturebox it all works well. This is done like this :
pictureBox1.Image = bildelisteDyr.bildeListe(r.Next(0, 20));
But I have three times where I need the code to check the value of the picturebox to do a something. I have one play sound button, one button that give a label a text and one button to check given answer from a textbox. None of them seems to work. Here are some code :
Give text to label :
if (pictureBox1.Image == bildelisteDyr.bildeListe(0))
{
svarPåOppgave.Text = "ÅL";
}
else if (pictureBox1.Image == bildelisteDyr.bildeListe(1))
{
svarPåOppgave.Text = "MAUR";
}
// etc.
Play sound button :
if (pictureBox1.Image == bildelisteDyr.bildeListe(0))
{
SoundPlayer player = new SoundPlayer();
player = new SoundPlayer("lyd/dyr/ål.wav");
player.PlaySync();
}
else if (pictureBox1.Image == bildelisteDyr.bildeListe(1))
{
SoundPlayer player = new SoundPlayer();
player = new SoundPlayer("lyd/dyr/enmaur.wav");
player.PlaySync();
}
// etc.
Checking if correct answer is given :
if (pictureBox1.Image == bildelisteDyr.bildeListe(0))
{
if (textBox1.Text.Trim().ToLower() == "ål")
{
riktigLyd.Play();
poengInt += 1;
textBox1.Text = "";
pictureBox1.Image = bildelisteDyr.bildeListe(tilfeldigBildet);
tekstTilLabel();
svarPåOppgave.Visible = false;
}
else
{
feilLyd.Play();
poengInt -= 1;
textBox1.Text = "";
}
String poengString = poengInt.ToString();
label1.Text = poengString;
textBox1.Select();
}
else if (pictureBox1.Image == bildelisteDyr.bildeListe(1))
{
if (textBox1.Text.Trim().ToLower() == "maur")
{
riktigLyd.Play();
poengInt += 1;
textBox1.Text = "";
pictureBox1.Image = bildelisteDyr.bildeListe(tilfeldigBildet);
tekstTilLabel();
svarPåOppgave.Visible = false;
}
else
{
feilLyd.Play();
poengInt -= 1;
textBox1.Text = "";
}
String poengString = poengInt.ToString();
label1.Text = poengString;
} // etc.
I would guess there was something wrong with the if statements like
if (textBox1.Text.Trim().ToLower() == "ål")
But I can´t seem to understand what?
To sum it up, when I debug the program I get the random picture from the other class. But when I press the buttons on the program nothing happens. No sound, no text to label and no checking of answer.
There's some unusual architectural choices here, but the specific problem you're facing is that you're re-creating the Bitmaps every time, and comparisons are performed by reference, not by value.
Change your bildelisteDyr class as follows:
public class bildelisteDyr
{
static Bitmap[] bildeListeInternal;
static bildelisteDyr() {
bildeListeInternal = new Bitmap[21];
bildeListeInternal[0] = Properties.Resources.ål;
//...
bildeListeInternal[20] = Properties.Resources.turtle;
}
public static Bitmap bildeListe (int index) {
return bildeListeInternal[index];
}
}
Some more resources on the conceptual problem:
== Operator
Value vs Reference Types

Shorting long if statement

I have spent hours making a tic tac toe game just using mainly if else statements, some of the code I just copy and pasted...
How would I just create one instance of the code, then refer to it later on? - when I need that code, instead of just copy and pasting massive lines of code each time. In this block of code, I am getting a random number between 1 to 10 this number will be stored in RI... then when it's Ai's turn the computer will randomly input an X in the button, then using this code it will check to determine if the computer has won. I hope that make sense =)
do
{
storeRI = rc.Next(0, 10); //storing random number into storeRI so it can be used later on in life.
if (storeRI == 1 && btn1.Text == "")
{
btn1.Text = "X";
Turn = 1;
if (btn1.Text == "X" & btn2.Text == "X" & btn3.Text == "X")
{
btn1.BackColor = Color.Green;
btn2.BackColor = Color.Green;
btn3.BackColor = Color.Green;
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
btn.Enabled = false;
}
else if (btn1.Text == "X" & btn4.Text == "X" & btn7.Text == "X")
{
btn1.BackColor = Color.Green;
btn4.BackColor = Color.Green;
btn7.BackColor = Color.Green;
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
btn.Enabled = false;
}
}
}
for example this code, is some of the code, that I have copied atleast 10 times, and it just makes me code look ugly and really hard to read.
for example this code, is some of the code, that I have copied atleast 10 times
Any time you have copied code, you should try to move it into a method. You can then just call the method directly. In your case, a method could easily accept the three buttons to affect, and work on them directly.
bool TestWin(Button btnA, Button btnB, button btnC)
{
if (btnA.Text == "X" & btnB.Text == "X" & btnC.Text == "X")
{
btnA.BackColor = Color.Green;
btnB.BackColor = Color.Green;
btnC.BackColor = Color.Green;
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
{
btn.Enabled = false;
}
return true;
}
return false;
}
if (!TestWin(btn1, btn2, btn3))
TestWin(btn1, btn4, btn7);
The refactoring technique you may want to look into is Consolidate Duplicate Conditional Fragments
if (btn1.Text == "X" & btn2.Text == "X" & btn3.Text == "X")
{
btn2.BackColor = Color.Green;
btn3.BackColor = Color.Green;
}
else if (btn1.Text == "X" & btn4.Text == "X" & btn7.Text == "X")
{
btn4.BackColor = Color.Green;
btn7.BackColor = Color.Green;
}
else
{
return/break/continue; // hard to tell which you what as you have a do without a corresponding while
}
btn1.BackColor = Color.Green;
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
{
btn.Enabled = false;
}
if (btn1.Text == "X")
{
btn1.BackColor = Color.Green;
if(btn2.Text == "X" & btn3.Text == "X")
btn2.BackColor = Color.Green;
btn3.BackColor = Color.Green;
}
else if (btn4.Text == "X" & btn7.Text == "X")
{
btn4.BackColor = Color.Green;
btn7.BackColor = Color.Green;
}
XScore += 1;
lblPScoreX.Text = XScore.ToString();
foreach (Button btn in buttonList)
{
btn.Enabled = false;
}
}
Nothing wrong with a long if else statement; it's better to have long readable code than short unmanageable code.
The one thing I can see that might help is to add in a method (with some changed to match your types):
public void ChangeButtonColor(Color thisColor, params Button[] buttons)
{
foreach (Button thisButton in buttons)
{
thisButton.BackColor = thisColor
}
}
then you can just add in to you code:
ChangeButtonColor(Color.Green, btn1, btn2, btn3);
This would save you some duplicated code.

Categories