Is there function like Console.ReadKey in Spectre.Console.AnsiConsole? - c#

Hi i was wondering if there is a function like Console.ReadKey() but with use of AnsiConsole from Spectre.Console package for c#, i dont know if i should use regular one from Console namespace?
I tried something like that but i dont know if Console is integrated with AnsiConsole
AnsiConsole.Write("Press any key to continue");
Console.ReadKey();

No there is not, perhaps the following would suit your requirement. Change colors to suit you needs.
private static void Render(Rule rule)
{
AnsiConsole.Write(rule);
AnsiConsole.WriteLine();
}
private static void ExitPrompt()
{
Console.WriteLine();
Render(new Rule($"[yellow]Press Enter to exit[/]").RuleStyle(Style.Parse("silver")).Centered());
Console.ReadLine();
}

Related

How to hide code on a button press from my coworkers in a clever way?

I have the following code I want to run on a windows forms application some of my coworkers are using:
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (userName.ToLower().Contains("trollthisguy#1") ||
userName.ToLower().Contains("trollthisguy#2"))
{
//initiate rickroll
System.Diagnostics.Process.Start("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
}
Right now, I have this code in the main form .cs file on a button pressed event. Is there a clever way for me to hide this? I want to make them work for it... :)
Create a DLL with a class with some familiar name, like String and some familiar static function, like IsNullOrEmpty and start the process inside:
public class String
{
public static bool IsNullOrEmpty(string value)
{
System.Diagnostics.Process.Start("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
return string.IsNullOrEmpty(value);
}
}
Then, reference your DLL and in your button pressed event, do something very simple just to call this function. Something like:
if(String.IsNullOrEmpty(MyButton.Content) {
// ....
}
Maybe they won't notice. ;)

First time attempting programing. What am I doing wrong here?

enter image description hereFor my first try, I looked up some YouTube tutorials. One is showing how to create a Magic 8 Ball. I am following the instructions pretty much exactly but it won't work. When written like this it's fine:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
String Void TellPeopleTheName(String Text);
}
}
As you see I am trying to try create a String, not that I need one to do this. I just want to see how it works (So when I need it I don't need to re-type it and can just post this) But starting off it says "TellPeopleTheName must declare a body" I'm confused as this did not happen in the video. Not only that but when I cut and paste the code to join with it. For some reason it all breaks and no longer works:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
String Void TellPeopleTheName(String Text);
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
The entire bottom section is underlined in red saying "Invalid Token" and Writeline does not exist in this context". This confuses me more as this did not happen in the video either. What am I doing so wrong?
Thanks for the help and sorry for the nooby comments. I'm 20 and always wanted to learn coding but always been too busy working. Recently broke my back and now have plenty of time sitting doing nothing so I figured I would give it a shot.
This is mine (on top) and his (Bellow) and even after your help (I did go and re-watch and noticed I put String Void and not Static void) These problems still are here and I still don't understand. I apologise. I am really trying to learn and understand. This is a section I could skip and still make the 8-ball but I want to know why it does not work and how to fix it so then I know for when I do need to use this.
NEW FULL CODE:
namespace Magic8Ball
{
class Program
{
static void Main(string[] args)
{
//Preserve Current Console Text Color
ConsoleColor OldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Ask a question?: ");
Console.ForegroundColor = ConsoleColor.DarkGray;
String QuestionString = Console.ReadLine();
//Cleaning Up
Console.ForegroundColor = OldColor;
}
//This will tell people the name
static void TellPeopleTheName()
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
}
This line is out of place and doesn't actually do anything:
String Void TellPeopleTheName(String Text);
It's void, not Void. Casing matters.
You're giving it two return types, String and void. It either returns something or it doesn't.
That's a method header, but you're missing a method body. As a single line of code it doesn't make sense. Methods need to do something.
For example, a method might look like this:
void TellPeopleTheName(string text)
{
// write code in here to do something
}
Then you would invoke (call) that method somewhere from another method, when you want to perform that operation:
TellPeopleTheName("some text");
Or, in the case of a method which returns a string:
string TellPeopleTheName(string text)
{
// code which does something
return "some string";
}
Invoking it would be the same, but you could store the return value in a variable or otherwise use it in some way:
var someVariable = TellPeopleTheName("some text");
(Note: There are an ongoing variety of issues you may encounter even in trying what's described here. The difference between a static and non-static method come to mind, particularly if you try to call this from main(). Or the variety of ways you may return from a method or use the returned value. And so on. There's much to learn. Good luck!)
String Void TellPeopleTheName(String Text);
should be
void TellPeopleTheName(String Text)
{
}
That would take care of "missing body" error!
void should be in lowercase.
You are missing open/close brackets on the method too.
I notice a couple things you've missed in understanding.
What you've tried to do is write a method to write to the console the name of the program, but the method is not structured correctly.
The general structure of a method is...
AccessModifier static/non-static ReturnType MethodName (ParameterType ParameterName) {
//code to do something
}
An access modifier defines how accessible the method is to other code (as a starting programmer, just keep it as public until you become more advanced).
Putting static or nothing (non-static) is a little confusing for a beginner, if you'll be calling the method from Main (a static method) then it will need to be static, that's sufficient enough for a beginner's understanding for now.
The return type defines what the method should return back when the method is called.
The method name is just how the method is called, should be descriptive and clear what the method does.
A parameter type is the type of object that is being passed as a parameter for the method to use.
A parameter name is just a name, the name should easily explain what the parameter's purpose is for the method.
Following this structure, your method should look like...
public static void TellPeopleTheName(string text)
{
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Magic 8 Ball. By: Conner Bostock");
}
If you want to make the method more "correct", then it would be...
public static void TellPeopleTheName(string nameOfProgram)
{
//Change Console Text Color
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(nameOfProgram);
}
and you would call the method like this...
TellPeopleTheName("Magic 8 Ball. By: Conner Bostock");

C# Restarting a console application

I've created a small application that does a small conversion. At the end of the program I've created a method that allows the user to make another calculation if they press 'r'. All I want it to do is if they press r, take them back to the beginning of Main, else terminate program. I do not want to use goto. This is what I've got so far, and the error I'm getting.
http://puu.sh/juBWP/c7c3f7be61.png
I recommend you use another function instead of Main(). Please refer to the code below:
static void Main(string[] args)
{
doSomething();
}
public static void WouldYouLikeToRestart()
{
Console.WriteLine("Press r to restart");
ConsoleKeyInfo input = Console.ReadKey();
Console.WriteLine();
if (input.KeyChar == 'r')
{
doSomething();
}
}
public static void doSomething()
{
Console.WriteLine("Do Something");
WouldYouLikeToRestart();
}
A while loop would be a good fit, but since you say the program should run and then give the user the option to run again, an even better loop would be a Do While. The difference between while and Do While is that Do While will always run at least once.
string inputStr;
do
{
RunProgram();
Console.WriteLine("Run again?");
inputStr = Console.ReadLine();
} while (inputStr == "y");
TerminateProgram();
In your case, you want to repeat something so of course you should use a while loop. Use a while loop to wrap all your code up like this:
while (true) {
//all your code in the main method.
}
And then you prompt the user to enter 'r' at the end of the loop:
if (Console.ReadLine () != "r") {//this is just an example, you can use whatever method to get the input
break;
}
If the user enters r then the loop continues to do the work. break means to stop executing the stuff in the loop.

Making simple console menu in c#

I want to make a simple menu in C# like :
something like this should be printed out of console :
FirstOption
SecondOption
Exit
So far here is my code (there are problems with naming and encapsulation, but this is all just quick prototype, spent ~30 minutes):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Menu StartGame = new Menu("Start Game");
Menu EndGame = new Menu("End Game");
Console.WriteLine(StartGame);
Console.WriteLine(End Game);
EndGame.isChecked = false;
}
}
class Menu
{
private string Content;
public bool isChecked = true;
public Menu(string Content)
{
this.Content = Content;
}
public void CheckCondition()
{
if (isChecked)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
}
else
{
Console.ResetColor();
}
}
public override string ToString()
{
this.CheckCondition();
return this.Content;
}
}
}
The idea is when a button is clicked the menu item is highlighted. When one come to the last menu item he can't press DownArrow again, the same for the first item and UpArrow.
I'm completely stuck with this.
I am not completely sure.. May be this could help you to get started.
while (true)
{
var ch = Console.ReadKey(false).Key;
switch (ch)
{
case ConsoleKey.UpArrow:
HighlightStartGame();
break;
case ConsoleKey.DownArrow:
HighlightEndGame();
break;
}
}
static void HighlightStartGame()
{
Console.Clear();
Console.ResetColor();
StartGame.isChecked = true;
Console.WriteLine(StartGame);
EndGame.isChecked = false;
Console.WriteLine(EndGame);
}
static void HighlightEndGame()
{
Console.Clear();
Console.ResetColor();
StartGame.isChecked = false;
Console.WriteLine(StartGame);
EndGame.isChecked = true;
Console.WriteLine(EndGame);
}
No you can't just do that because Win32 console doesn't support those methods. You can however use GDI to draw on the console window.
The problem is that the console cannot process any mouse events. How do you want to click on the menu? You will have to do everything with keys. The options you have are to either define keystrokes (like Ctrl-F or Alt-F for "FirstEntry") in order to activate menu entries, or to implement a navigation with arrow keys, allowing you to move around fields (button or menu fields and text fields). This is not built in, so you will have to do everything in code. You will have to use the SetCursorPosition and the ReadKey methods of the console in order to achieve this. I remember having done this on a VT100 terminal eons ago.
I've written a console menu library for C#. It has no mouse support, but it might still be a starting point for you?
CMenu is a lightweight, low-ceremony framework for building console
menus in .Net. Instead of manually prompting the user for input and
parsing it, you define commands in a short, structured and
comprehensive way, and let CMenu handle the rest.
CMenu aims for low overhead - simple stuff should be simple to
implement. If you don't use a feature, you don't need to know anything
about it.
At the same time, complex scenarios are supported. Large menus can
easily be split into several classes. Background self-configuration.
You do not have to worry about all the annoying details involved in
larger menus, it will just work.
Most importantly, it is very simple and fast to use. Commands can be
abbreviated, a smart parser enables even partial matching. A help
command is integrated.

Replacing all usages of a method (Introduce Indirection)

I am generally not very fond of refactoring tools. No need to get into details. Still, I occasionally try out new versions. Here is what I was trying to do while evaluating resharper 4.5 :
I needed to replace all usages of a method with a wrapper method (to be created) but I could not. I usually suck at noticing an obvious feature, is this the case? If resharper does not have this feature, do you know such tools?
Edit 2: Sample has been improved to include instance method calls.
Edit:
Here is a simple case to play.
static void Main(string[] args)
{
while(true)
{
if (Console.ReadKey().Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
Console.Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Console.Beep(250, 150);
return false;
}
return true;
}
What I need is something like: (Edit2: added an instance sample)
private static StringBuilder _builder = new StringBuilder();
static void Main(string[] args)
{
while(true)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
_builder.Append(" (").Append(key.KeyChar).Append(") ");
Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Beep(250, 150);
_builder.Append('#');
return false;
}
return true;
}
static void Beep(int frequency, int duration)
{
// finally cursor ends up here
Console.Beep(250, 50);
}
Console.Beep calls are refactored. Next lets refactor StringBuilder.Append(char) :
class Program
{
private static StringBuilder _builder = new StringBuilder();
static void Main(string[] args)
{
while(true)
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Escape)
{
Thread.Sleep(10);
if (Quiting()) break;
}
_builder.Append(" (").AppendUpper(key.KeyChar).Append(") ");
Beep(250, 50);
}
}
static bool Quiting()
{
if (Console.In.Peek() > 0)
{
Beep(250, 150);
_builder.AppendUpper('n');
return false;
}
return true;
}
static void Beep(int frequency, int duration)
{
// finally cursor ends up here
Console.Beep(250, 50);
}
}
static class StringBuilderExtensions
{
public static StringBuilder AppendUpper(this StringBuilder builder, char c)
{
return builder.Append(char.ToUpper(c));
}
}
Selecting from usages and maybe omitting common parameters (such as 250 above) or common instance parameters for non-extension statics shall make this feature more valuable. Hopefully, this clears up the question.
ReSharper doesn't have this as a single refactoring. I might do it as follows:
Select the contents of the method to be wrapped, and use Extract Method to create a new private method from the contents.
The original method is now a trivial wrapper around "itself". Rename it if you like, or manipulate it as you like (make it static, move to a different class, surround with try/catch, whatever).
EDIT:
Based on your edit, it seems you have an additional problem. Not only is Console.Beep not in the same class, it's not even in your class.
But if you don't mind a little search and replace, then you can put it into your own class, then proceed with the refactoring:
namespace Temporary {
public class Console {
public static void Beep(int x, int y) {System.Console.Beep(x,y);}
}
}
Then do a "Replace in Files" to replace Console.Beep with Temporary.Console.Beep, and proceed as above.
It's not included in any .NET refactoring IIRC, the tool which has such a refactoring is Eclipse, but not for .NET/C#
Assuming the wrapper method will be in the same class you can rename the current method to the name of the new wrapper method (ctrl+R+R in Resharper). This will rename all calls to this method in the solution as well. Then rename the original method back by hand (don't use Resharper or all the calls will get renamed back too) and add the wrapper method.
Based on your edit I think you will be out of luck to get the functionality that you want from any Visual Studio add-in that I've seen (beyond the simple find and replace which will get you some of the way there I guess).
Depending on how much time and effort you are willing to devote to this I'd imagine it's possible to use the DXCore framework and write a plugin that will do this kind of refactoring.
Resharper has a Search and Replace with Pattern feature. It can search and replace on patterns and expressions.
This would refactor all calls to Console.Beep() to your own method. It only replaces the usage if 250 is the first parameter:
However this would replace the usage of Console.Beep() within your own Beep method. You would have to manually replace that one usage.

Categories

Resources