I am trying to add exception handling with a corresponding message box to a Universal Windows app. I wanted to just use TryParse or Try-Catch, but I can't figure out what the equivalent to a message box is in universal windows apps. I'm not particularly worried about the aesthetics of it now, as long as whatever I do conforms to UWP standards so I don't get into bad habits moving forward.
Here is my C#:
double INCHES = 1;
double FEET = 12;
double YARDS = 36;
double userDist, convertDist, distFrom, distTo;
string unitOfMeasure;
private void convertButton_Click(object sender, RoutedEventArgs e)
{
unitOfMeasure = null;
distFrom = 1;
distTo = 1;
if (inputTextBox.Text != "")
{
userDist = double.Parse(inputTextBox.Text);
if (listBox1.SelectedIndex >= 0 || listBox2.SelectedIndex >= 0)
{
switch (listBox1.SelectedIndex)
{
case 0:
distFrom = INCHES;
unitOfMeasure = " in";
break;
case 1:
distFrom = FEET;
unitOfMeasure = " ft";
break;
case 2:
distFrom = YARDS;
unitOfMeasure = " yd";
break;
}
switch (listBox2.SelectedIndex)
{
case 0:
distTo = INCHES;
unitOfMeasure = " in";
break;
case 1:
distTo = FEET;
unitOfMeasure = " ft";
break;
case 2:
distTo = YARDS;
unitOfMeasure = " yd";
break;
}
convertDist = (userDist * distFrom) / distTo;
outputTextBlock.Text = convertDist.ToString("n2") + unitOfMeasure;
}
else
{
//MessageDialog dialog = new MessageDialog("Please select 'From' and 'To' units.");
}
}
else
{
//MessageDialog dialog = new MessageDialog("Please input a number to convert.");
}
}
private void clearButton_Click(object sender, RoutedEventArgs e)
{
inputTextBox.Text = "";
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
outputTextBlock.Text = "";
distFrom = 1;
distTo = 1;
}
private void exitButton_Click(object sender, RoutedEventArgs e)
{
App.Current.Exit();
}
I think the code you commented out should work if you also add -
await dialog.ShowAsync();
Like Brian said
MessageDialog dialog = new MessageDialog("Please select 'From' and 'To' units.");
await dialog.ShowAsync();
should work. I'd also add that you need to mark convertButton_Click as an async method:
private async void convertButton_Click(object sender, RoutedEventArgs e)
Related
How do I also make it so that if all 3 slots have a jackpot image, the user wins 5x their bet
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Slot_Machine
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random rnd = new Random();
int a, b, c, move, wins,losses, bid;
int balance = 100;
If the user clicks the quit button, the program ends
private void QuitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
If the user presses the reset button, the game restarts
private void ResetBtn_Click(object sender, EventArgs e)
{
Application.Restart();
}
This function subtracts the bid from the balance before the slots start running
void Before_Game_Result()
{
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance - bid;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
}
This function decides whether or not the user won their bid
void Game_Result()
{
if (System.Convert.ToInt32(a) == b && System.Convert.ToInt32(b) == c)
{
wins++;
WinLbl.Text = "Wins: " + wins;
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance + (bid * 2);
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
else
{
if ((System.Convert.ToInt32(a) == b && System.Convert.ToInt32(b) != c) || (System.Convert.ToInt32(a) == c && System.Convert.ToInt32(b) != c) ||
(System.Convert.ToInt32(b) == c && System.Convert.ToInt32(a) != c))
{
wins++;
WinLbl.Text = "Wins: " + wins;
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance + bid;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
else
{
losses++;
LossesLbl.Text = "Losses: " + losses;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
}
if (balance <= 0)
{
MessageBox.Show("You don't have any money!! SCRAM");
this.Close();
}
}
This function validates that the user enters a valid bid before pressing the bid button
private void BidBtn_Click(object sender, EventArgs e)
{
if(BidAmountTxt.Text =="")
{
MessageBox.Show("input a bid first!!");
}
else
{
int x = Convert.ToInt32(BidAmountTxt.Text);
bool success = false;
if(x <= balance)
{
success = true;
}
if(success)
{
Before_Game_Result();
timer1.Enabled = true;
BidAmountTxt.Enabled = false;
BidBtn.Enabled = false;
BidAmountTxt.BackColor = Color.Black;
}
else
{
MessageBox.Show("INVALID - please enter a bid lower or equal to your balance");
BidAmountTxt.Clear();
}
}
}
**This function runs the slots **
private void timer1_Tick(object sender, EventArgs e)
{
move++;
if (move < 30)
{
a = rnd.Next(5);
b = rnd.Next(5);
c = rnd.Next(5);
switch(a)
{
case 1:
Slot1.Image = Properties.Resources.basketball3;
break;
case 2:
Slot1.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot1.Image = Properties.Resources.volleyball;
break;
case 4:
Slot1.Image = Properties.Resources.hockey_puck;
break;
}
switch (b)
{
case 1:
Slot2.Image = Properties.Resources.basketball3;
break;
case 2:
Slot2.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot2.Image = Properties.Resources.volleyball;
break;
case 4:
Slot2.Image = Properties.Resources.hockey_puck;
break;
}
switch (c)
{
case 1:
Slot3.Image = Properties.Resources.basketball3;
break;
case 2:
Slot3.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot3.Image = Properties.Resources.volleyball;
break;
case 4:
Slot3.Image = Properties.Resources.hockey_puck;
break;
}
}
else
{
timer1.Enabled = false;
move = 0;
Game_Result();
}
}
}
}
There's lot of ways to do what you want. My take on this is that a little abstraction would go a long way. Starting with an ImageList where you can select pictures by index.
Assign it to the ImageList property of the controls (e.g. Label) you are using to display a slot "wheel".
public MainForm()
{
InitializeComponent();
labelJackpot.Visible= false;
Slot1.ImageList = imageList;
Slot2.ImageList = imageList;
Slot3.ImageList = imageList;
}
Then you could abstract those index values to an enum.
enum SlotImage
{
Jackpot,
Basketball,
SoccerBall,
VolleyBall,
HockeyPuck,
}
Which simplifies your "wheel spinner" in your timer tick handler:
Label[] Slots => new [] { Slot1, Slot2, Slot3 };
SlotImage[] SlotImages { get; } = Enum.GetValues(typeof(SlotImage)).Cast<SlotImage>().ToArray();
private void timer1_Tick(object sender, EventArgs e)
{
move++;
if (move < 30)
{
foreach (var slot in Slots)
{
slot.ImageIndex= rnd.Next(SlotImages.Length);
}
}
else
{
timer1.Enabled = false;
move = 0;
// Probably goes in GameResult but here's how.
var isJackpot = Slots.All(_ => ((SlotImage)_.ImageIndex).Equals(SlotImage.Jackpot));
labelJackpot.Visible = isJackpot;
Game_Result();
}
}
Doing it in this manner would make the wheels comparable by int. So, one solution to your question is to use this System.Linq expression to see whether you've hit the jackpot.
isJackpot = Slots.All(_ => ((SlotImage)_.ImageIndex).Equals(SlotImage.Jackpot));
Well, here I have a tic-tac-toe app. I have made it properly, but it has a small issue. When it is a draw, it shows me the message like 8 times and I am not able to correct this alone. Everything else is alright. In the tutorial I have found it doesn't adress this specific issue, so what am I doing wrong?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] table = new string[9];
int countTurn = 0;
public String returnSymbol(int turn)
{
if (turn % 2 == 0)
{
return "O";
}
else
return "X";
}
public System.Drawing.Color determineColor(string symbol)
{
if(symbol.Equals("X"))
{
return System.Drawing.Color.LawnGreen;
}
else
{
return System.Drawing.Color.Aqua;
}
}
public void CheckDraw()
{
int count = 0;
for (int i = 0; i < table.Length; i++)
{
if (table[i] != null)
count++;
if (count == 9)
{
MessageBox.Show("That's a draw!", "We have no winner :(", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
public void checkForWinner()
{
for(int i=0;i<8; i++)
{
string combination = "";
int one=0, two=0, three = 0;
switch(i)
{
case 0:
combination = table[0] + table[4] + table[8];
one = 0;
two = 4;
three = 8;
break;
case 1:
combination = table[2] + table[4] + table[6];
one = 2;
two = 4;
three = 6;
break;
case 2:
combination = table[0] + table[1] + table[2];
one = 0;
two = 1;
three = 2;
break;
case 3:
combination = table[3] + table[4] + table[5];
one = 3;
two = 4;
three = 5;
break;
case 4:
combination = table[6] + table[7] + table[8];
one = 6;
two = 7;
three = 8;
break;
case 5:
combination = table[0] + table[3] + table[6];
one = 0;
two = 3;
three = 6;
break;
case 6:
combination = table[1] + table[4] + table[7];
one = 1;
two = 4;
three = 7;
break;
case 7:
combination = table[2] + table[5] + table[8];
one = 2;
two = 5;
three = 8;
break;
}
if(combination.Equals("OOO"))
{
changeColor(one);
changeColor(two);
changeColor(three);
MessageBox.Show("O has won the game!", "We have a winner!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
if(combination.Equals("XXX"))
{
changeColor(one);
changeColor(two);
changeColor(three);
MessageBox.Show("X has won the game!", "We have a winner!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
CheckDraw();
}
}
}
public void reset()
{
button1.Text = "";
button2.Text = "";
button3.Text = "";
button4.Text = "";
button5.Text = "";
button6.Text = "";
button7.Text = "";
button8.Text = "";
button9.Text = "";
button1.BackColor=System.Drawing.Color.White;
button2.BackColor=System.Drawing.Color.White;
button3.BackColor=System.Drawing.Color.White;
button4.BackColor=System.Drawing.Color.White;
button5.BackColor=System.Drawing.Color.White;
button6.BackColor=System.Drawing.Color.White;
button7.BackColor=System.Drawing.Color.White;
button8.BackColor=System.Drawing.Color.White;
button9.BackColor=System.Drawing.Color.White;
countTurn = 0;
table = new string[9];
}
public void changeColor(int number)
{
switch(number){
case 0:
button1.BackColor = System.Drawing.Color.OrangeRed;
break;
case 1:
button2.BackColor = System.Drawing.Color.OrangeRed;
break;
case 2:
button3.BackColor = System.Drawing.Color.OrangeRed;
break;
case 3:
button4.BackColor = System.Drawing.Color.OrangeRed;
break;
case 4:
button5.BackColor= System.Drawing.Color.OrangeRed;
break;
case 5:
button6.BackColor = System.Drawing.Color.OrangeRed;
break;
case 6:
button7.BackColor = System.Drawing.Color.OrangeRed;
break;
case 7:
button8.BackColor = System.Drawing.Color.OrangeRed;
break;
case 8:
button9.BackColor = System.Drawing.Color.OrangeRed;
break;
}
}
private void button1_Click(object sender, EventArgs e)
{
countTurn++;
table[0]=returnSymbol(countTurn);
button1.BackColor = determineColor(table[0]);
button1.Text = table[0];
checkForWinner();
}
private void button2_Click(object sender, EventArgs e)
{
countTurn++;
table[1] = returnSymbol(countTurn);
button2.BackColor = determineColor(table[1]);
button2.Text = table[1];
checkForWinner();
}
private void button3_Click(object sender, EventArgs e)
{
countTurn++;
table[2] = returnSymbol(countTurn);
button3.BackColor = determineColor(table[2]);
button3.Text = table[2];
checkForWinner();
}
private void button4_Click(object sender, EventArgs e)
{
countTurn++;
table[3] = returnSymbol(countTurn);
button4.BackColor = determineColor(table[3]);
button4.Text = table[3];
checkForWinner();
}
private void button5_Click(object sender, EventArgs e)
{
countTurn++;
table[4] = returnSymbol(countTurn);
button5.BackColor = determineColor(table[4]);
button5.Text = table[4];
checkForWinner();
}
private void button6_Click(object sender, EventArgs e)
{
countTurn++;
table[5] = returnSymbol(countTurn);
button6.BackColor = determineColor(table[5]);
button6.Text = table[5];
checkForWinner();
}
private void button7_Click(object sender, EventArgs e)
{
countTurn++;
table[6] = returnSymbol(countTurn);
button7.BackColor = determineColor(table[6]);
button7.Text = table[6];
checkForWinner();
}
private void button8_Click(object sender, EventArgs e)
{
countTurn++;
table[7] = returnSymbol(countTurn);
button8.BackColor = determineColor(table[7]);
button8.Text = table[7];
checkForWinner();
}
private void button9_Click(object sender, EventArgs e)
{
countTurn++;
table[8] = returnSymbol(countTurn);
button9.BackColor = determineColor(table[8]);
button9.Text = table[8];
checkForWinner();
}
private void TryAgainBtn_Click(object sender, EventArgs e)
{
reset();
}
}
}
The problem is that your CheckDraw method is called within the outer for loop for(int i=0;i<8; i++). Change CheckDraw to return a bool like so:
public bool CheckDraw()
{
int count = 0;
for (int i = 0; i < table.Length; i++)
{
if (table[i] != null)
count++;
if (count == 9)
{
MessageBox.Show("That's a draw!", "We have no winner :(", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return true;
}
}
return false;
}
And then in CheckForWinner() change
else
{
CheckDraw();
}
to
else
{
if (CheckDraw())
{
break;
}
}
As a side note: I think your implementation allows to change the status of fields that have already been played. So you can win the game by changing an O to an X...
You can actually simplify your CheckDraw function to the following
public void CheckDraw()
{
for (int i = 0; i < table.Length; i++)
{
//on the first `null` entry it can't be a draw anymore, so return
if (table[i] == null)
return;
}
//if the loop found a value in all cells it's a draw ...
MessageBox.Show("That's a draw!", "We have no winner :(", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
or even simpler if you use LINQ
public void CheckDraw()
{
if (table.All(x => x != null)) {
MessageBox.Show("That's a draw!", "We have no winner :(", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
But that function is not your real problem. The problem is in checkForWinner. You should exit once you found a winner. And only if none of the winning situations leads to a winner, check also for a draw.
public void checkForWinner()
{
for(int i=0;i<8; i++)
{
string combination = "";
int one=0, two=0, three = 0;
switch(i)
{
...
}
if(combination.Equals("OOO"))
{
...
MessageBox.Show("O has won the game!", "We have a winner!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return; //return from checkforWinner as we already have a winner
}
else if(combination.Equals("XXX"))
{
...
MessageBox.Show("X has won the game!", "We have a winner!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return; //return from checkforWinner as we already have a winner
}
}
//if we arrived here, it could still be a draw ...
checkDraw();
}
You could also dramatically simplify your checkForWinner if you create a List of winning situations beforehand and then just iterate over the situations and check it. Because the checking is always the same: Check if the three entries in the table are equal. If yes, the respective player has won the game ...
public void checkForWinner()
{
var winningList = new List<(int a, int b, int c)> {
(0, 1, 2),
(3, 4, 5),
//...
};
foreach (var t in winningList) {
if (table[t.a] != null && table[t.a] == table[t.b] && table[t.a] == table[t.c]) {
changeColor(t.a);
changeColor(t.b);
changeColor(t.c);
MessageBox.Show($"{table[t.a]} has won the game!", ...);
return; //return from checkforWinner as we already have a winner
}
}
//if we arrived here, it could still be a draw ...
CheckDraw();
}
And as said in another comment: Most of your button click handlers only differ in the index of the table lookup. You could easily attach a Tag to each button (or determine it even from the name of the button) so you could use the same clickhandler for all buttons instead of having to repeat the same code 9 times ...
Hi I have created a window calculator and it is working fine however, i want to be able to use my keyboard numbers as well for my calculator app . what do i do? here is my code
public partial class Form1 : Form
{
Double resultValue = 0;
String operationPerformed = "";
bool isOperationPerformed = false;
public Form1()
{
InitializeComponent();
}
private void button_click(object sender, EventArgs e)
{
if ((textBox_Result.Text == "0") || (isOperationPerformed))
textBox_Result.Clear();
isOperationPerformed = false;
Button button = (Button)sender;
if (button.Text == ".")
{
if (!textBox_Result.Text.Contains("."))
textBox_Result.Text = textBox_Result.Text + button.Text;
} else
textBox_Result.Text = textBox_Result.Text + button.Text;
}
private void operator_click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (resultValue != 0)
{
EqualsToBtn.PerformClick();
operationPerformed = button.Text;
labelCurrentOperation.Text = resultValue + " " + operationPerformed;
isOperationPerformed = true;
}else
{
operationPerformed = button.Text;
resultValue = Double.Parse(textBox_Result.Text);
labelCurrentOperation.Text = resultValue + " " + operationPerformed;
isOperationPerformed = true;
}
}
private void RefreshBtn_Click(object sender, EventArgs e)
{
textBox_Result.Text = "0";
}
private void CancelBtn_Click_1(object sender, EventArgs e)
{
textBox_Result.Text = "0";
resultValue = 0;
}
private void EqualsToBtn_Click_1(object sender, EventArgs e)
{
switch (operationPerformed)
{
case "+":
textBox_Result.Text = (resultValue + Double.Parse(textBox_Result.Text)).ToString();
break;
case "-":
textBox_Result.Text = (resultValue - Double.Parse(textBox_Result.Text)).ToString();
break;
case "*":
textBox_Result.Text = (resultValue * Double.Parse(textBox_Result.Text)).ToString();
break;
case "/":
textBox_Result.Text = (resultValue / Double.Parse(textBox_Result.Text)).ToString();
break;
}
resultValue = Double.Parse(textBox_Result.Text);
labelCurrentOperation.Text = "";
}
}
}
You can achieve it by subscribing to KeyDown event.
Fisrt, need to set KeyPreview to true.
public Form1()
{
InitializeComponent();
KeyPreview = true;
}
Then use swicth to judge which key pressed. Keys Enum
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.NumPad0:
case Keys.D0:
// Zero
buttonnum0.PerformClick(); // simulate pressing buttonnum0
break;
case Keys.NumPad1:
case Keys.D1:
// One
buttonnum1.PerformClick();
break;
// ... etc
case Keys.Oemplus:
case Keys.Add:
// Plus
buttonplus.PerformClick();
break;
default:
return;
}
e.Handled = true;
}
You can use the processcmdkey
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == ( Keys.Numpad0 | Keys.Numpad0)) { // just an example, handle the rest as you need
doSomething();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
I'm trying to build a simple calculator application in C# and I have no idea why it crashes when I do the following steps.
Enter 0.2
Click Subtraction
Enter 0
The application crashes immediately. I assume it is something to do with the Zero() function since that is what is executed when the Zero button is clicked. The conditional statements are meant to take care of instances where shouldn't occur like consecutive ciphers and so on. Here is the source code. The functions for the other digits are identical, by the way.
public partial class MainWindow : Window
{
protected double firstNumber, secondNumber;
protected string textBoxContents;
protected int selectedFunction;
public MainWindow()
{
InitializeComponent();
firstNumber = 0;
secondNumber = 0;
selectedFunction = 0;
textBoxContents = "0";
}
private void Zero(object sender, RoutedEventArgs e)
{
if (Convert.ToDouble(textBoxContents) > 0 || textBoxContents[textBoxContents.Length - 1] == '.')
{
if(selectedFunction != 0)
textBoxContents = textBoxContents + "0";
}
else if (textBoxContents == null)
{
textBoxContents = textBoxContents + "0";
}
ResultBox.Content = textBoxContents;
}
private void One(object sender, RoutedEventArgs e)
{
textBoxContents = textBoxContents + "1";
ResultBox.Content = textBoxContents;
}
private void Decimal(object sender, RoutedEventArgs e)
{
textBoxContents = textBoxContents + ".";
ResultBox.Content = textBoxContents;
}
private void Addition(object sender, RoutedEventArgs e)
{
firstNumber = Convert.ToDouble(textBoxContents);
textBoxContents = null;
selectedFunction = 1;
}
private void Subtraction(object sender, RoutedEventArgs e)
{
firstNumber = Convert.ToDouble(textBoxContents);
textBoxContents = null;
selectedFunction = 2;
}
private void Multiplication(object sender, RoutedEventArgs e)
{
firstNumber = Convert.ToDouble(textBoxContents);
textBoxContents = null;
selectedFunction = 3;
}
private void Division(object sender, RoutedEventArgs e)
{
firstNumber = Convert.ToDouble(textBoxContents);
textBoxContents = null;
selectedFunction = 4;
}
private void Result(object sender, RoutedEventArgs e)
{
secondNumber = Convert.ToDouble(textBoxContents);
double thirdNumber = 0;
switch (selectedFunction)
{
case 1:
thirdNumber = firstNumber + secondNumber;
break;
case 2:
thirdNumber = firstNumber - secondNumber;
break;
case 3:
thirdNumber = firstNumber * secondNumber;
break;
case 4:
thirdNumber = firstNumber / secondNumber;
break;
default:
break;
}
textBoxContents = Convert.ToString(thirdNumber);
ResultBox.Content = textBoxContents;
}
private void ClearEverything(object sender, RoutedEventArgs e)
{
textBoxContents = null;
firstNumber = 0;
secondNumber = 0;
selectedFunction = 1;
ResultBox.Content = Convert.ToString(0);
}
private void ToggleNegative(object sender, RoutedEventArgs e)
{
if (Convert.ToDouble(textBoxContents) != 0)
{
textBoxContents = Convert.ToString(Convert.ToDouble(textBoxContents) * -1);
ResultBox.Content = textBoxContents;
}
else
ResultBox.Content = Convert.ToString(0);
}
}
private void Zero(object sender, RoutedEventArgs e)
{
if (Convert.ToDouble(textBoxContents) > 0 ||
textBoxContents[textBoxContents.Length - 1] == '.')
{
if(selectedFunction != 0)
textBoxContents = textBoxContents + "0";
}
else if (textBoxContents == null)
{
textBoxContents = textBoxContents + "0";
}
ResultBox.Content = textBoxContents;
}
That logic seems a tidge off. If the value of the text box is empty then it's going to blow up because of the indexer on the other side of the ||. I think this can be rewritten to say:
private void Zero(object sender, RoutedEventArgs e)
{
var dblVal = Convert.ToDouble(textBoxContents.Text);
textBoxContents.Text = dblVal.ToString();
ResultBox.Content = textBoxContents.Text;
}
In other words, if the text box is empty the conversion will yield 0.0; if it ends in a 1. it will yield 1.0; if it's .5 it will yield 0.5. Just leverage the Convert.
The decimal separator is localized, are you sure that you are using the right culture ("," instead of ".")?
If that's the issue, check out this Stack Question
textBoxContents is null after clicking on the substraction button.
Instead of textBoxContents = null; use textBoxContents = "0"; or textBoxContents = string.Empty;. Why do you set it to null anyway?
Calling textBoxContents.Length in your Zero method causes a NullReferenceException.
As others mentioned before your logic in Zero() seams a bit circuitous and and certainly could be smaller.
in Subtraction function you are doing
textBoxContents = null;
and then in zero you have
textBoxContents[textBoxContents.Length - 1]
thats why it crashes
you should check for null before any operation on textBoxContents
I want to play a video like that guy did [link].
I'm working on C# Windows Form Application (not NXA).
But I don't know how.
I tried using Microsoft.DirectX.AudioVideoPlayback but no luck.
This is what I tried so far :
OpenFileDialog rihanna = new OpenFileDialog();
if(rihanna.ShowDialog() == DialogResult.OK)
{
video = new Video(rihanna.FileName);
video.Owner = panel1;
video.Stop();
}
Now what can i do? I tried using video class but as I said it just did not work.
I'm able to compile but when I'm running the program, I don't see the form window.
using Microsoft.DirectX.AudioVideoPlayback;
namespace Play_Video
{
public partial class Form1 : Form
{
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;
public Form1()
{
InitializeComponent();
VolumeTrackBar.Value = 4;
}
private void timer1_Tick(object sender, EventArgs e)
{
PlayingPosition = CalculateTime(vdo.CurrentPosition);
txtStatus.Text = PlayingPosition + "/" + Duration;
if (vdo.CurrentPosition >= vdo.Duration)
{
timer1.Stop();
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdo.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
else
vdoTrackBar.Value += 1;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.Stop();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
openFileDialog1.Title = "Select video file..";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.DefaultExt = ".avi";
openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
if (openFileDialog1.FileName != "")
{
Form1.ActiveForm.Text = openFileDialog.FileName + " - Anand Media Player";
vdo = new Video(openFileDialog.FileName);
vdo.Owner = panel1;
panel1.Width = 700;
panel1.Height = 390;
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdoTrackBar.Minimum = 0;
vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
if (vdo != null)
{
if (vdo.Playing)
{
vdo.Pause();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
}
else
{
vdo.Play();
timer1.Start();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.pause;
}
}
}
private void btnStop_Click(object sender, EventArgs e)
{
vdo.Stop();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
public string CalculateTime(double Time)
{
string mm, ss, CalculatedTime;
int h, m, s, T;
Time = Math.Round(Time);
T = Convert.ToInt32(Time);
h = (T / 3600);
T = T % 3600;
m = (T / 60);
s = T % 60;
if (m < 10)
mm = string.Format("0{0}", m);
else
mm = m.ToString();
if (s < 10)
ss = string.Format("0{0}", s);
else
ss = s.ToString();
CalculatedTime = string.Format("{0}:{1}:{2}", h, mm, ss);
return CalculatedTime;
}
private void VolumeTrackBar_Scroll(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.Audio.Volume = CalculateVolume();
}
}
public int CalculateVolume()
{
switch (VolumeTrackBar.Value)
{
case 1:
return -1500;
case 2:
return -1000;
case 3:
return -700;
case 4:
return -600;
case 5:
return -500;
case 6:
return -400;
case 7:
return -300;
case 8:
return -200;
case 9:
return -100;
case 10:
return 0;
default:
return -10000;
}
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
}
private void vdoTrackBar_Scroll(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.CurrentPosition = vdoTrackBar.Value;
}
}
private void Form1_Load(object sender, EventArgs e)
{
MaximizeBox = false;
}
private void exitToolItem_Click(object sender,EventArgs e)
{
Application.Exit();
}
}
}
Okey Namespace is clear:
using Microsoft.DirectX.AudioVideoPlayback;
Some Global Variables in Form:
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;
And now in your Button or what else to open:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
openFileDialog1.Title = "Select video file..";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.DefaultExt = ".avi";
openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
vdo = new Video(openFileDialog.FileName);
vdo.Owner = panel1;
panel1.Width = 700;
panel1.Height = 390;
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdoTrackBar.Minimum = 0;
vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);
And in some other Button Code to Start/Pause:
if (vdo.Playing)
{
vdo.Pause();
btnPlay.Text= "Play";
}
else
{
vdo.Play();
btnPlay.Text= "Pause";
}
BTW:
Don't name variables/members or something else in your Code after Girls...
If your aren't sure how to name it, there are some Guidelines here.
The goal is to provide a consistent set of naming
conventions that results in names that make immediate sense to
developers.
For AudioVideoPlayback to work, you'll need to add the AudioVideoPlayback reference, with Reference > Add Reference > Browse > C: > Windows > Microsoft.Net > DirectX for managed code > 1.0.2902.0 > Microsoft.DirectX.AudioVideoPlayback.dll