I know this question is asked many times but i havent found the right answer for my problem.
My problem is i have a WinForm and i like to press multiple keys to make something xD but if i try to press numpad7, 8 and 4 or any other combination
then it wont work it shows just nothing but i have pressed all this keys
i have tried this
private void GameScreen_KeyDown(object sender, KeyEventArgs e) {
try {
switch (e.KeyCode) {
case Keys.NumPad0:
Console.WriteLine(e.KeyData);
changeButtonsColor();
break;
case Keys.NumPad1:
gb_7.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
case Keys.NumPad2:
gb_8.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
case Keys.NumPad3:
gb_9.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
case Keys.NumPad4:
gb_4.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
case Keys.NumPad5:
gb_5.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
case Keys.NumPad6:
gb_6.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
case Keys.NumPad7:
gb_1.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
case Keys.NumPad8:
gb_2.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
case Keys.NumPad9:
gb_3.BackColor = Color.MediumSpringGreen;
Console.WriteLine(e.KeyData);
break;
}
} catch (Exception) {
Console.WriteLine("fail");
}
}
please help me...
This cannot be fixed. Because of how keyboards work, you can press 2 keys at the same time, but as soon as you start pressing 3 at a time, only certain combinations will work. There is no way you can modify the coding to fix this, unless you change what keys you are pressing.
Related
I work on csharp i face issue i can't access element inside switch case statement as
case RoleNames.REQ:
so How to do that ?
I create enum as below :
public enum RoleNames
{
REQ,
HRED,
PLNG,
REC,
CEO
}
2- I call enum to get first element by switch case on Main function console .
static void Main(string[] args)
{
RoleNames rn=new RoleNames();
switch (rn)
{
case RoleNames.REQ:
break;
case RoleNames.HRED:
break;
case RoleNames.PLNG:
break;
case RoleNames.REC:
break;
case RoleNames.CEO:
break;
default:
break;
}
}
I need to access first element on switch as
RoleNames.REQ:
when debug code above switch go direct to default break
so what change i can do on my code to access first element case RoleNames.REQ:
I was desiring to clean up my code a bit for a battleship program that I was creating. There is a 2D array gameboard that holds char values pertaining to each of the ships found on the board, i.e. a battleship on the gameboard would be represented as 'BBBB'.
The program already runs, but the portion which checks whether the user's selected coordinate contains a char value that pertains to a ship seems messy, and I do not know of a way to make it look cleaner. Before this, it was implemented as a bunch of if else-if statements, and that didn't really look too clean either. Any help or pointers to guide me in the right direction would be great. Thanks.
switch (board.Grid[userSelectedRow, userSelectedCol])
{
case 'C':
carrier_C_HitCounter++;
hitCounter++;
if (carrier_C_HitCounter != shipList[0].Length)
{
Console.WriteLine("You struck a ship!\n");
}
else
Console.WriteLine("You sunk their carrier!\n");
break;
case 'B':
battleship_HitCounter++;
hitCounter++;
if (battleship_HitCounter != shipList[1].Length)
{
Console.WriteLine("You struck a ship!\n");
}
else
Console.WriteLine("You sunk their battleship!\n");
break;
case 'S':
submarine_S_HitCounter++;
hitCounter++;
if (submarine_S_HitCounter != shipList[2].Length)
{
Console.WriteLine("You struck a ship!");
}
else
Console.WriteLine("You sunk their submarine!");
break;
case 's':
submarine_s_HitCounter++;
hitCounter++;
if (submarine_s_HitCounter != shipList[3].Length)
{
Console.WriteLine("You struck a ship!");
}
else
Console.WriteLine("You sunk their submarine!");
break;
case 'D':
destroyer_D_HitCounter++;
hitCounter++;
if (destroyer_D_HitCounter != shipList[4].Length)
{
Console.WriteLine("You struck a ship!");
}
else
Console.WriteLine("You sunk their destroyer!");
break;
case 'd':
destroyer_d_HitCounter++;
hitCounter++;
if (destroyer_d_HitCounter != shipList[5].Length)
{
Console.WriteLine("You struck a ship!");
}
else
Console.WriteLine("You sunk their destroyer!");
break;
default:
Console.WriteLine("No ships were hit.");
break;
}
// Change the hit location to 'X'
board.SetChar(userSelectedRow, userSelectedCol, 'X');
The code that is being repeated the most is your check for what ship it is and generating the associated message:
if (carrier_C_HitCounter != shipList[0].Length)
{
Console.WriteLine("You struck a ship!\n");
}
else
Console.WriteLine("You sunk their carrier!\n");
You could define an enum and a function to generate the messages like so to clean up the switch statement a bit:
enum Ship
{
"carrier",
"battleship",
"submarine",
"destroyer"
}
public void getMessage(int number, int counter){
if (counter != shipList[number].Length)
{
Console.WriteLine("You struck a ship!");
}
else
Console.WriteLine("You sunk their " + (Ship)number + " !");
}
Then call it from the switch like:
switch (board.Grid[userSelectedRow, userSelectedCol])
{
case 'C':
carrier_C_HitCounter++;
hitCounter++;
getMessage(0,carrier_C_HitCounter);
break;
case 'B':
battleship_HitCounter++;
hitCounter++;
getMessage(1,battleship_HitCounter);
break;
case 'S':
submarine_S_HitCounter++;
hitCounter++;
getMessage(2,submarine_S_HitCounter);
break;
case 's':
submarine_s_HitCounter++;
hitCounter++;
getMessage(2,submarine_s_HitCounter);
break;
case 'D':
destroyer_D_HitCounter++;
hitCounter++;
getMessage(3,destroyer_D_HitCounter);
break;
case 'd':
destroyer_d_HitCounter++;
hitCounter++;
getMessage(3,destroyer_d_HitCounter);
break;
default:
Console.WriteLine("No ships were hit.");
break;
}
// Change the hit location to 'X'
board.SetChar(userSelectedRow, userSelectedCol, 'X');
I'm assuming shipList is global but otherwise modify the function header to pass that in too. The most important thing in making you code look cleaner is to look for large repeating chunks and try to find a way to "reroute" it. Hope this helps Derek :) Welcome to SO
I'm a complete Newbie to the world of programming, yet I really wish to learn a lot as quick as possible and now came up to a problem that I can't find to solute just via researching and "learning- by doing" (Trying around).
Basically I'm trying to work on a small console- based TextAdventure in C Sharp (With VisualStudios) Now I came to a Case- Switch (Offering the User some Options to read and walk through), but I wish to add a Y/N Confirmation in case the User decides to take a different path. For now it's only for the starting point of the story:
Does the User want to go into "The Wilds", "The City", "The Farm". Something as simple as that just in addition: "Are you sure (Y/N)?" leading the No to return the given choices.
Thank you all in advance and stay healthy!
Menu mainMenu = new Menu(prompt, options);
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
private void TakeYourLeave()
{
WriteLine("\nYou are about to take your leave... Are you sure ? (Y/N)");
ReadKey();
Environment.Exit(0);
}
private void VisitTheMemorial()
{
Clear();
//FILLER//
WriteLine("You may proceed by the press of any button.");
ReadKey(true);
RunMainMenu();
}
private void EnterTheWorld()
{
string prompt = "Where would you like to start your journey?";
string[] options = { "The Slums", "The Wilds", "The City", "The Farm" };
Menu startMenu = new Menu(prompt, options);
int selectedIndex = startMenu.Run();
BackgroundColor = ConsoleColor.White;
switch (selectedIndex)
{
case 0:
ForegroundColor = ConsoleColor.Black;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 1:
ForegroundColor = ConsoleColor.Green;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 2:
ForegroundColor = ConsoleColor.Red;
WriteLine("\n ||Small Description||Are you sure to take this path? (Y/N)");
break;
case 3:
ForegroundColor = ConsoleColor.Yellow;
WriteLine("\n ||Small Description|| Are you sure to take this path? (Y/N)");
break;
}
In this case, you need to take care of a few things:
Make sure that the entire switch-statement logic is in a while-loop, as such:
while (True) {
int selectedIndex = mainMenu.Run();
switch (selectedIndex)
{
case 0:
EnterTheWorld();
break;
case 1:
VisitTheMemorial();
break;
case 2:
TakeYourLeave();
break;
default:
break;
}
}
Check with your function if the input given is "No", if such, then immeditely return so your function exits before any navigation
private void VisitTheMemorial()
{
userInput = readKeyFunction();
if (userInput == "no") {
return;
}}
Finally, if the user doesn't select no, just do nothing and let the function go on
It is best to handle the 'Are you sure?' inside the menu.Run(), and return a value to the selectedIndex after the confirmation. Also avoid using while loop at the main flow in this case.
Note: you have to think in a modular way. Consider your Menu class as a module which handles user choice. The main flow does not have to bother about the confirmation by the user, it just have to process the final result of the user.
Another suggestion: Use enums instead of integers wherever possible for multiple choices.
Can someone please tell me why my switch statement is not working? In my program I have a text box with the choices of 'Billing', 'Tech Support', 'Retention', 'Customer Service'. My switch statement is saying if that text box is = xxx then show a form I build and hide everything else.
Currently only the billing and other option works?!
<
private void cbDept_SelectedIndexChanged(object sender, EventArgs e)
{
string reason = cbDept.Text;
switch (reason)
{
case "Billing":
gbBilling.Show();
gbTechSupport.Hide();
gbCS.Hide();
gbRetention.Hide();
lbOtherReason.Hide();
txtOther.Hide();
break;
case "Tech Support":
gbTechSupport.Show();
gbBilling.Hide();
gbCS.Hide();
gbRetention.Hide();
lbOtherReason.Hide();
txtOther.Hide();
break;
case "Retention":
gbRetention.Show();
gbBilling.Hide();
gbTechSupport.Hide();
gbCS.Hide();
lbOtherReason.Hide();
txtOther.Hide();
break;
case "Customer Service":
gbCS.Show();
gbBilling.Hide();
gbTechSupport.Hide();
gbRetention.Hide();
lbOtherReason.Hide();
txtOther.Hide();
break;
case "Other":
txtOther.Show();
lbOtherReason.Show();
gbCS.Hide();
gbBilling.Hide();
gbTechSupport.Hide();
gbRetention.Hide();
break;
default:
gbCS.Hide();
gbBilling.Hide();
gbTechSupport.Hide();
gbRetention.Hide();
break;
}
}
>
It seems to me that there is some misspelling in the other options. Check the values of reason before reaching the switch.
Why does the following work (compile):
public void SaveCurrentTab(string currentTabIndex)
{
if (currentTabIndex == MainInfoPnl.ClientID)
PartialSave1();
else if (currentTabIndex == ContactInfoPnl.ClientID)
PartialSave2();
else if (currentTabIndex == BankInfoPnl.ClientID)
PartialSave3();
else if (currentTabIndex == ServicesPnl.ClientID)
PartialSave4();
else if (currentTabIndex == AttachmentsPnl.ClientID)
PartialSave5();
}
But, the following does not?
public void SaveCurrentTab(string currentTabIndex)
{
switch (currentTabIndex)
{
case MainInfoPnl.ClientID:
PartialSave1();
break;
case ContactInfoPnl.ClientID:
PartialSave2();
break;
case BankInfoPnl.ClientID:
PartialSave3();
break;
case ServicesPnl.ClientID:
PartialSave4();
break;
case AttachmentsPnl.ClientID:
PartialSave5();
break;
}
}
Presumably because MainInfoPnl.ClientID isn't a compile-time constant. It may be public static readonly for example, which isn't the same as const. If that doesn't help, show us more about the code and the error message you're getting.
The case statements must be constant strings for a switch - an if condition has no such restriction.
A switch in C# only works with constant values. For values determined at runtime, use a if-else construction.
Try this:
public void SaveCurrentTab(string currentTabIndex)
{
switch (Convert.ToInt32(currentTabIndex))
{
case (int)MainInfoPnl.ClientID:
PartialSave1();
break;
case (int)ContactInfoPnl.ClientID:
PartialSave2();
break;
case (int)BankInfoPnl.ClientID:
PartialSave3();
break;
case (int)ServicesPnl.ClientID:
PartialSave4();
break;
case (int)AttachmentsPnl.ClientID:
PartialSave5();
break;
}
}