I am trying to make a menu with three buttons (in order: Play, Options, Exit) in which only selected button has a border and that is controlled with arrows UP and DOWN. Unfortunately nothing seems to be happening when buttons are pressed atm. Here's the code:
public partial class
{
int i = 0;
List<Button> menuButtons = new List<Button>();
Button selectedButton = new Button();
public Menu()
{
InitializeComponent();
menuButtons.Add(btnPlay);
menuButtons.Add(btnOptions);
menuButtons.Add(btnExit);
selectedButton = menuButtons[i];
if (menuButtons[i] == selectedButton)
{
menuButtons[i].FlatAppearance.BorderSize = 1;
}
}
private void Menu_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
if (i < menuButtons.Count)
{
i++;
}
else if (i >= menuButtons.Count)
{
i = 0;
}
}
if (e.KeyCode == Keys.Up)
{
if (i > 0)
{
i--;
}
else if (i <= 0)
{
i = menuButtons.Count;
}
}
if (e.KeyCode == Keys.Enter)
{
switch (i)
{
case 0:
btnPlay.PerformClick();
break;
case 1:
btnOptions.PerformClick();
break;
case 2:
btnExit.PerformClick();
break;
}
}
}
Have a nice day :)
There are two problems in your code. The first one is in the first two if statements. You are correctly changing the index, but you are not setting the border to the new selected button. You must remove the border of the previously selected button and set the new selected button's border.
The second is that you forgot to set click events for your buttons, so they'll do nothing when clicked. Here's how your code should be:
public partial class
{
int i = 0;
List<Button> menuButtons = new List<Button>();
Button selectedButton = new Button();
public Menu()
{
InitializeComponent();
//Assigning click events for the buttons.
btnPlay.Click += BtnPlay_Click;
btnOptions.Click += BtnOptions_Click;
btnExit.Click += BtnExit_Click;
menuButtons.Add(btnPlay);
menuButtons.Add(btnOptions);
menuButtons.Add(btnExit);
selectedButton = menuButtons[i];
if (menuButtons[i] == selectedButton)
{
menuButtons[i].FlatAppearance.BorderSize = 1;
}
}
private void Menu_KeyDown(object sender, KeyEventArgs e)
{
//Removing border from previously selected button.
menuButtons[i].FlatAppearance.BorderSize = 0;
if (e.KeyCode == Keys.Down)
{
if (i < menuButtons.Count)
{
i++;
}
else if (i >= menuButtons.Count)
{
i = 0;
}
}
if (e.KeyCode == Keys.Up)
{
if (i > 0)
{
i--;
}
else if (i <= 0)
{
i = menuButtons.Count;
}
}
//Setting border for the newly selected button.
menuButtons[i].FlatAppearance.BorderSize = 1;
if (e.KeyCode == Keys.Enter)
{
switch (i)
{
case 0:
btnPlay.PerformClick();
break;
case 1:
btnOptions.PerformClick();
break;
case 2:
btnExit.PerformClick();
break;
}
}
}
private void BtnExit_Click(object sender, EventArgs e)
{
//Code for the Exit button.
}
private void BtnOptions_Click(object sender, EventArgs e)
{
//Code for the Options button.
}
private void BtnPlay_Click(object sender, EventArgs e)
{
//Code for the Play button.
}
}
PS: pay attention to unnecessary code like the the selectedButton variable and the if statement in the constructor. They do not affect the functionality, but may hinder later code maintenance.
Related
Here is a picture of when I run the program. I want the user to be able to only type on the current line. They shouldn't be able to edit the lines above.
Here is the link to the github if you want to downlaod it to use it for yourself. https://github.com/TeddyRoche/Calculator
Here is the code that is controlling the whole program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Calculator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
float number_Initial = 0;
float prev_Answer = 0;
List<float> number_List = new List<float>();
List<string> equations = new List<string>();
bool valid = true;
int key_Press = 0;
int maxLines = 0;
string lastLine = "";
public MainWindow()
{
InitializeComponent();
}
private void NumPressedButton(int i)
{
if (valid == false)
{
MessageBox.Show("Please enter only numbers.");
displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
else
{
if (key_Press < 12)
{
this.displayText.Text += i;
number_Initial = number_Initial * 10 + i;
key_Press++;
}
}
valid = true;
}
private void NumPressedKeyboard(int i)
{
if (valid == false)
{
MessageBox.Show("Please enter only numbers.");
displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
else
{
if (key_Press < 12)
{
number_Initial = number_Initial * 10 + i;
key_Press++;
}
}
valid = true;
}
private void OutputSymbol(string x)
{
switch (x)
{
case "+":
equations.Add("add");
break;
case "-":
equations.Add("sub");
break;
case "*":
equations.Add("mul");
break;
case "/":
equations.Add("div");
break;
}
}
private void SymbolPressedButton(String x)
{
if (lastLine == "")
{
this.displayText.AppendText("Ans");
number_List.Add(prev_Answer);
this.displayText.AppendText(x);
OutputSymbol(x);
key_Press = key_Press + 4;
}
else
{
if (number_Initial == 0)
{
this.displayText.AppendText(x);
OutputSymbol(x);
key_Press++;
}
else
{
number_List.Add(number_Initial);
this.displayText.AppendText(x);
OutputSymbol(x);
number_Initial = 0;
key_Press++;
}
}
}
private void SymbolPressedKeyboard(String x)
{
if (lastLine == "")
{
this.displayText.AppendText("Ans");
number_List.Add(prev_Answer);
OutputSymbol(x);
key_Press = key_Press + 4;
}
else
{
if (number_Initial == 0)
{
OutputSymbol(x);
key_Press++;
}
else
{
number_List.Add(number_Initial);
OutputSymbol(x);
number_Initial = 0;
key_Press++;
}
}
}
//Display____________________________________________________________________________________________________________________________________________________
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
maxLines = displayText.LineCount;
if(maxLines > 0)
{
lastLine = displayText.GetLineText(maxLines - 1);
}
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
//check to see if what the user presses is a number or one of the appropriate symbols allowed
//if not sets valid to false
valid = true;
if(e.Key < Key.D0 || e.Key > Key.D9)
{
if(e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
{
valid = false;
if (e.Key == Key.Add || e.Key == Key.Subtract || e.Key == Key.Multiply || e.Key == Key.Divide || e.Key == Key.Enter)
{
valid = true;
}
}
}
if(valid == true)
{
//Performing functions when a certain key is pressed
switch (e.Key)
{
case Key.NumPad0:
case Key.D0:
NumPressedKeyboard(0);
break;
case Key.NumPad1:
case Key.D1:
NumPressedKeyboard(1);
break;
case Key.NumPad2:
case Key.D2:
NumPressedKeyboard(2);
break;
case Key.NumPad3:
case Key.D3:
NumPressedKeyboard(3);
break;
case Key.NumPad4:
case Key.D4:
NumPressedKeyboard(4);
break;
case Key.NumPad5:
case Key.D5:
NumPressedKeyboard(5);
break;
case Key.NumPad6:
case Key.D6:
NumPressedKeyboard(6);
break;
case Key.NumPad7:
case Key.D7:
NumPressedKeyboard(7);
break;
case Key.NumPad8:
case Key.D8:
NumPressedKeyboard(8);
break;
case Key.NumPad9:
case Key.D9:
NumPressedKeyboard(9);
break;
case Key.Add:
SymbolPressedKeyboard("+");
break;
case Key.Subtract:
SymbolPressedKeyboard("-");
break;
case Key.Divide:
SymbolPressedKeyboard("/");
break;
case Key.Multiply:
SymbolPressedKeyboard("*");
break;
case Key.Enter:
Equals_Equation();
break;
}
}
else if(valid == false)
{
MessageBox.Show("Please enter only numbers.");
//displayText.Text = displayText.Text.Remove(displayText.Text.Length - 1);
}
}
//Display____________________________________________________________________________________________________________________________________________________
//Numbers ___________________________________________________________________________________________________________________________________________________
private void _0_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(0);
}
private void _1_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(1);
}
private void _2_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(2);
}
private void _3_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(3);
}
private void _4_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(4);
}
private void _5_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(5);
}
private void _6_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(6);
}
private void _7_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(7);
}
private void _8_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(8);
}
private void _9_Click(object sender, RoutedEventArgs e)
{
NumPressedButton(9);
}
//Numbers____________________________________________________________________________________________________________________________________________________
//Equations__________________________________________________________________________________________________________________________________________________
private void Divide_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("/");
}
private void Multiply_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("*");
}
private void Subtract_Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("-");
}
private void Add__Click(object sender, RoutedEventArgs e)
{
SymbolPressedButton("+");
}
protected void Equals_Equation()
{
if(equations.Count != 0)
{
if(this.displayText.Text.StartsWith("1") || this.displayText.Text.StartsWith("2") || this.displayText.Text.StartsWith("3") || this.displayText.Text.StartsWith("4") || this.displayText.Text.StartsWith("5") || this.displayText.Text.StartsWith("6") || this.displayText.Text.StartsWith("7") || this.displayText.Text.StartsWith("8") || this.displayText.Text.StartsWith("9") || this.displayText.Text.StartsWith("0"))
{
number_List.Add(number_Initial);
this.displayText.AppendText("\n");
//loop that goes through the equations list and does the appropriate calculations
//Does Multiplication and Division first
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "mul")
{
number_List[s] = number_List[s] * number_List[s + 1];
}
else if (equations[s] == "div")
{
number_List[s] = number_List[s] / number_List[s + 1];
}
}
//Then does Addition and Subtraction next
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "add")
{
number_List[0] = number_List[0] + number_List[s + 1];
}
else if (equations[s] == "sub")
{
number_List[0] = number_List[0] - number_List[s + 1];
}
}
//changes the display to show the answer and creates a new line for the user to continue
this.displayText.Text += number_List[0];
number_Initial = number_List[0];
number_List.Clear();
prev_Answer = number_Initial;
//number_List.Add(number_Initial);
number_Initial = 0;
equations.Clear();
this.displayText.AppendText("\n");
this.displayText.PageDown();
displayText.Select(displayText.Text.Length, 0);
}
else if (this.displayText.Text.StartsWith("A"))
{
number_List.Insert(0, prev_Answer);
number_List.Add(number_Initial);
this.displayText.AppendText("\n");
//loop that goes through the equations list and does the appropriate calculations
//Does Multiplication and Division first
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "mul")
{
number_List[s] = number_List[s] * number_List[s + 1];
}
else if (equations[s] == "div")
{
number_List[s] = number_List[s] / number_List[s + 1];
}
}
//Then does Addition and Subtraction next
for (int s = 0; s < equations.Count(); s++)
{
if (equations[s] == "add")
{
number_List[0] = number_List[0] + number_List[s + 1];
}
else if (equations[s] == "sub")
{
number_List[0] = number_List[0] - number_List[s + 1];
}
}
//changes the display to show the answer and creates a new line for the user to continue
this.displayText.Text += number_List[0];
number_Initial = number_List[0];
number_List.Clear();
prev_Answer = number_Initial;
//number_List.Add(number_Initial);
number_Initial = 0;
equations.Clear();
this.displayText.AppendText("\n");
this.displayText.PageDown();
displayText.Select(displayText.Text.Length, 0);
}
}
else
{
}
key_Press = 0;
}
private void Equals_Click(object sender, RoutedEventArgs e)
{
Equals_Equation();
}
//Clears all stored data so the user can start from scratch
private void Clear_Click(object sender, RoutedEventArgs e)
{
number_List.Clear();
number_Initial = 0;
equations.Clear();
this.displayText.Clear();
key_Press = 0;
}
//Equations__________________________________________________________________________________________________________________________________________________
}
}
I havent found much that has helped with only allowing the user to edit the current line. I see a lot with not allowing the user to edit the whole textBox.
I want the user to only be able to edit the current line. Right know I can use the arrow keys or click with my mouse on the previous lines and can edit them and I dont want them to be allowed to do this.
Here is a quick example. Hopefully this gives you enough info.
XAML
<TextBox
AcceptsReturn="True"
TextWrapping="Wrap"
VerticalScrollBarVisibility="Auto"
PreviewTextInput="TextBox_PreviewTextInput"/>
Code Behind
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (sender is not TextBox box) //semi-redundant safety check
return;
//make sure there is text, also make sure there is a newline in the box
if (string.IsNullOrEmpty(box.Text) || (!box.Text.Contains('\n') && !box.Text.Contains('\r')))
return;
//through some testing I found the \r would be there without a \n so I include both for completeness
var lastReturn = Math.Max(box.Text.LastIndexOf('\r'), box.Text.LastIndexOf('\n'));
if (box.CaretIndex <= lastReturn)
e.Handled = true;
}
This solution can be expanded on, but it mainly prevents the Text from changing whenever Text is entered on any line but the last. I like it as you can also move the Text Caret around to get standard functionality still (highlighting, selection, etc.)
I need help I have a set PictureBox (40), and I need to select these pictureboxes with arrows. I mean when I'm on the first picture and press right arrow key (border changing - selected), the border of the first should switch to none and next one switch to border FixedSingle.
One idea is:
if (keyData == Keys.Right) {
if (PictureBox1.BorderStyle == BorderStyle.FixedSingle) {
PictureBox1.BorderStyle = BorderStyle.None;
PictureBox2.BorderStyle = BorderStyle.FixedSingle;
} else if (PictureBox2.BorderStyle == BorderStyle.FixedSingle) {
pictu.....
}
}
but this method takes too much time so I'm looking for a simpler method.
Can somebody help me find a simpler way to do this?
EDIT new code:
namespace testPics
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown_1(object sender, KeyEventArgs e)
{
changePictureBox(e.KeyData);
}
List<PictureBox> myPictureBoxes;
int index;
public void iniPictureBoxes()
{
myPictureBoxes = new List<PictureBox>();
myPictureBoxes.Add(pictureBox1);
myPictureBoxes.Add(pictureBox2);
myPictureBoxes.Add(pictureBox3);
index = 0;
}
public void changePictureBox(Keys keyData)
{
myPictureBoxes[index].BorderStyle = BorderStyle.None;
if (keyData == Keys.Right)
{
if (index < myPictureBoxes.Count - 1)
index++;
}
else if (keyData == Keys.Left)
{
if (index > 0)
index--;
}
myPictureBoxes[index].BorderStyle = BorderStyle.FixedSingle;
}}}
You could create a list of pictureboxes.
Then for example you can add an indexer (just to keep it simple).
The indexer is an int (or in your case can be a byte) that stores the index of the currently selected picturebox.
If the user presses "right arrow" key just change the border of the current indexed picturebox increment the indexer and update "the now indexd picturebox".
List<PictureBox> myPictureBoxes;
int index;
public void iniPictureBoxes()
{
myPictureBoxes = new List<PictureBox>();
myPictureBoxes.Add(pictureBox1);
myPictureBoxes.Add(pictureBox2);
index = 0;
}
public void changePictureBox(Keys keyData)
{
myPictureBoxes[index].BorderStyle = BorderStyle.None;
if(keyData == Keys.Right)
{
if(index < myPictureBoxes.Count - 1)
index++;
}
else if(keyData == Keys.Left)
{
if(index>0)
index--;
}
myPictureBoxes[index].BorderStyle = BorderStyle.FixedSingle;
}
this just sets the borderstyle. If you want to really select the picturebox you also need to implement it (picturebox.select();)
It may be better to create the pictureboxes generically. So you don't have to do add all of them manually to the List.
Here is the generic code for adding pictureboxes (in this case 5):
public void iniPictureBoxes()
{
myPictureBoxes = new List<PictureBox>();
for (int i = 0; i < 5; i++)
{
PictureBox tempPB = new PictureBox();
tempPB.Location = new Point(i * 15, 10);
tempPB.Size = new Size(10, 10);
tempPB.BackColor = Color.Black;
Controls.Add(tempPB);
myPictureBoxes.Add(tempPB);
}
index = 0;
}
and here the way to add an event: just double click the event u want to have.
Then a method is being auto generated for you. And you should change it to
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
changePictureBox(e.KeyData);
}
I have a custom Datagrid, in that datagrid I change the way we select element.
I have some feature added to the selection, like :
When we select element, it's like the "Ctrl" key was press.
When we click on a selected row, the row become unselected.
When we do a multiple selection, all the row change the selectedValue for the one that the first row is going to have.
When we do a multiple selection (mouse down, move, then mouse up) with Right click it's reversing the selected value of the rows.
It's a DataGrid extension, so I am coding only in C#.
For doing that I added event handle on PreviewMouseDown and MouseUp of for the datagridrow.
private enum ButtonClicked {Left, Middle, Right};
private ButtonClicked m_oMouseButtonClicked;
private void PreviewMouseDownHandler(object sender, MouseButtonEventArgs e)
{
DataGridRow row = sender as DataGridRow;
if (e.LeftButton == MouseButtonState.Pressed)
{
row.IsSelected = !row.IsSelected;
m_oMouseButtonClicked = ButtonClicked.Left;
}
else if (e.RightButton == MouseButtonState.Pressed)
{
//row.IsSelected = !row.IsSelected;
m_oMouseButtonClicked = ButtonClicked.Right;
}
row.CaptureMouse();
row.MouseMove += row_MouseMove;
e.Handled = true;
}
void row_MouseMove(object sender, MouseEventArgs e)
{
Point oPosFromThis = e.GetPosition(this);
if (oPosFromThis.Y > this.ActualHeight)
{
}
else if (oPosFromThis.Y < 0)
{
}
}
void Row_MouseUp(object sender, MouseButtonEventArgs e)
{
int nStart;
int nEnd;
DataGridRow row = sender as DataGridRow;
row.ReleaseMouseCapture();
row.MouseMove -= row_MouseMove;
int nStartRowIndex = ItemContainerGenerator.IndexFromContainer(row);
Point oPosFromRow = e.MouseDevice.GetPosition(row);
int nEndRowIndex = nStartRowIndex + (int)Math.Floor(oPosFromRow.Y / row.ActualHeight);
if (nStartRowIndex < nEndRowIndex)
{
nStart = Math.Max(nStartRowIndex, 0);
nEnd = Math.Min(nEndRowIndex, Items.Count - 1);
}
else
{
nStart = Math.Max(nEndRowIndex, 0);
nEnd = Math.Min(nStartRowIndex, Items.Count - 1);
}
for (; nStart <= nEnd; ++nStart)
{
DataGridRow oTmp = ((DataGridRow)ItemContainerGenerator.ContainerFromIndex(nStart));
if (m_oMouseButtonClicked == ButtonClicked.Left)
{
oTmp.IsSelected = row.IsSelected;
}
else if (m_oMouseButtonClicked == ButtonClicked.Right)
{
oTmp.IsSelected = !oTmp.IsSelected;
}
}
e.Handled = true;
}
I give the mouse capture to my row i clicked, to be able to catch the mouseUp even if i go outside the datagrid.
But with my code, I lost a feature that i would like to have. The auto scrolling when I do a multiple selection and i go under or upper the datagrid. I know that iI will have to add MouseMove Handler to do it, but for now i am stuck cause I don't know how to do it.
I finally found a solution by try-error attempts. I added method to get the scrollviewer element, then i am starting a Timer to execute the scroll alone.
public claa AAA
{
private enum ButtonClicked {Left, Middle, Right};
private ButtonClicked m_oMouseButtonClicked;
private DispatcherTimer m_oTimer;
private double m_nScrollOffset;
private ScrollViewer m_oScrollBar;
public IcuAlertGrid()
{
this.Initialized += IcuAlertGrid_Initialized;
this.Loaded += IcuAlertGrid_Loaded;
m_oTimer = new DispatcherTimer();
m_oTimer.Tick += m_oTimer_Tick;
m_oTimer.Interval = new TimeSpan(2500000);
}
void IcuAlertGrid_Initialized(object sender, EventArgs e)
{
setStyle0(true);
//throw new NotImplementedException();
}
void IcuAlertGrid_Loaded(object sender, RoutedEventArgs e)
{
m_oScrollBar = GetScrollViewer(this);
}
void m_oTimer_Tick(object sender, EventArgs e)
{
if (m_oScrollBar != null)
{
m_oScrollBar.ScrollToVerticalOffset(m_oScrollBar.VerticalOffset + m_nScrollOffset);
}
}
private void PreviewMouseDownHandler(object sender, MouseButtonEventArgs e)
{
DataGridRow row = sender as DataGridRow;
if (e.LeftButton == MouseButtonState.Pressed)
{
row.IsSelected = !row.IsSelected;
m_oMouseButtonClicked = ButtonClicked.Left;
}
else if (e.RightButton == MouseButtonState.Pressed)
{
//row.IsSelected = !row.IsSelected;
m_oMouseButtonClicked = ButtonClicked.Right;
}
row.CaptureMouse();
row.MouseMove += row_MouseMove;
e.Handled = true;
}
private void row_MouseMove(object sender, MouseEventArgs e)
{
DataGridRow oRow = sender as DataGridRow;
Point oPosFromThis = e.GetPosition(this);
if (oPosFromThis.Y < 0)
{
m_nScrollOffset = -1.0;
m_oTimer.Start();
}
else if (this.ActualHeight < oPosFromThis.Y)
{
m_nScrollOffset = 1.0;
m_oTimer.Start();
}
else
{
m_oTimer.Stop();
}
}
private void Row_MouseUp(object sender, MouseButtonEventArgs e)
{
int nStart;
int nEnd;
m_oTimer.Stop();
DataGridRow row = sender as DataGridRow;
row.ReleaseMouseCapture();
row.MouseMove -= row_MouseMove;
int nStartRowIndex = ItemContainerGenerator.IndexFromContainer(row);
Point oPosFromRow = e.MouseDevice.GetPosition(row);
int nEndRowIndex = nStartRowIndex + (int)Math.Floor(oPosFromRow.Y / row.ActualHeight);
if (nStartRowIndex < nEndRowIndex)
{
nStart = Math.Max(nStartRowIndex, 0);
nEnd = Math.Min(nEndRowIndex, Items.Count - 1);
}
else
{
nStart = Math.Max(nEndRowIndex, 0);
nEnd = Math.Min(nStartRowIndex, Items.Count - 1);
}
for (; nStart <= nEnd; ++nStart)
{
DataGridRow oTmp = ((DataGridRow)ItemContainerGenerator.ContainerFromIndex(nStart));
if (m_oMouseButtonClicked == ButtonClicked.Left)
{
oTmp.IsSelected = row.IsSelected;
}
else if (m_oMouseButtonClicked == ButtonClicked.Right)
{
oTmp.IsSelected = !oTmp.IsSelected;
}
}
e.Handled = true;
}
private static ScrollViewer GetScrollViewer(DependencyObject p_oParent)
{
ScrollViewer child = default(ScrollViewer);
int numVisuals = VisualTreeHelper.GetChildrenCount(p_oParent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(p_oParent, i);
child = v as ScrollViewer;
if (child == null)
{
child = GetScrollViewer(v);
}
if (child != null)
{
break;
}
}
return child;
}
}
i'm new to C# (and programming at all) and i'm trying to write an 'XO' game along with ASP.NET
i'm getting a problem after the first player clicks a button.
turns doesn't switch and any click after the 1st does nothing. what is wrong with my code ?
public partial class GamePage : System.Web.UI.Page
{
Player player1 = new Player();
Player player2 = new Player();
int turn;
protected void Page_Load(object sender, EventArgs e)
{
this.turn = 0;
if (!IsPostBack)
{
Label1.Visible = true;
}
if (turn == 0)
{
Label1.Text = (Session["player1"] as Player).getname();
}
else
{
Label1.Text = (Session["player2"] as Player).getname();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["p1"] = player1;
Session["p2"] = player2;
player1.setsymbol("X");
player2.setsymbol("O");
if (Button1.Text == "")
{
if (turn == 0)
{
Button1.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button1.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Button2.Text == "")
{
if (turn == 0)
{
Button2.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button2.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (Button3.Text == "")
{
if (turn == 0)
{
Button3.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button3.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
// this is an example - i have the same lines from button1 to 9
Everytime page renders, you set turn to 0 in Page_Load. Because Page_Load is executed upon every page load, you won't get any other value and this is probably the major issue here.
To properly support the lifetime of such variables that should keep value upon consecutive requests, wrap them in simple property:
public int turn
{
get
{
if ( Session["turn"] != null )
return (int)Session["turn"];
return 0; // default value if not set before
}
set
{
Session["turn"] = value;
}
}
This way everytime you refer to turn in your code, setting it to 0 or 1 or comparing the value to 0 or 1, you will refer to the same value, possibly stored during previous request(s).
this.turn=0; should be executed only when IsPostBack is false. Move this line inside if in your Page_Load.
I like to write a small Application to paste/insert some text at my current cursor position.
For Example: I am in Word: Here I like to press CTRL+ALT+1 and it will insert some text at my pointer position. Or I have an open Internet-Explorer window, Notepad, Adobe, ..., or any other application
I started with listening the shortcuts with a global Keyboard hook library.
And the event for the hotkeys is working fine for me. But now I got stuck because I found no way to paste/insert the text at the position from my cursor. I tried using SendMessage/PostMessage, or SendKeys.
The problem with SendMessage is that I was not able to get every window and SendKeys is fired multiple times if you are using it togheter with the Keyboard hook library...
Any ideas how I could continue?
Code for the Hotkeys:
namespace Developper_Dashboard
{
public partial class Form1 : Form
{
globalKeyboardHook gkh = new globalKeyboardHook();
private bool IsADown = false;
private bool IsBDown = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Hide the MainForm
this.Opacity = 0;
// Listening Keys
gkh.HookedKeys.Add(Keys.LControlKey);
gkh.HookedKeys.Add(Keys.LMenu);
gkh.HookedKeys.Add(Keys.NumPad1);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
}
void gkh_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.LControlKey)
{
IsADown = false;
}
if (e.KeyCode == Keys.LMenu)
{
IsBDown = false;
}
if (!IsADown | !IsBDown)
{
this.Opacity = 0;
}
//e.Handled = true;
}
void gkh_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.LControlKey)
{
IsADown = true;
}
if (e.KeyCode == Keys.LMenu)
{
IsBDown = true;
}
if (IsADown && IsBDown)
{
this.Opacity = 1;
}
if (IsADown && IsBDown && e.KeyCode == Keys.NumPad1)
{
// Here the code for paste/insert...?
}
}
}
}