-1

Recently begun to learn C#. One of the tasks contain the example, which I haven't been able to release. Here it is.

using System.Windows.Forms;
class ShowForm
{
    public static void Main()
    {
        MessageBox.Show("Windows Forms!");
        MessageBox.Show("Windows Forms with title", "title");        
        if (MessageBox.Show("Are you sure I want to continue?", "title",
            MessageBoxButtons.OKCancel) == DialogResult.OK)
            System.Console.WriteLine("You pressed OK");
        else System.Console.WriteLine("You pressed Cancel");       
        System.Console.WriteLine("You can show messages in Console as well");
        System.Console.ReadKey();
    }
}

The error it shows is: System.InvalidOperationException: "Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read." I've tried to change preferences in the solution, but it didn't help. Would be thankful for any advise.

  • what are you wanting to express? – Daniel A. White Mar 24 '21 at 18:14
  • You could try Process.Launch("cmd.exe"). Investigate that, you can attach to its input as well as output stream. – JimmyV Mar 24 '21 at 18:17
  • 4
    You cannot use `Console.ReadKey()` in WinForms, there's no Console. And you don't need it. This is a UI platform, User input comes from the UI. Your `Main` should not contain that code either. You cannot work on an UI app as if it was a Console app. Move your code to a Form class and get User input using TextBoxes, ComboBoxes, DataGrids etc. Or build a Console app. – Jimi Mar 24 '21 at 18:18
  • 1
    You may want to have a look at this link https://stackoverflow.com/a/10818929/11741043 – Ali Ihsan Elmas Mar 24 '21 at 18:18
  • 2
    You can change the application type to "Console" instead of "Windows", then you can have both the console and message boxes. It's in Project Properties->Application – PMF Mar 24 '21 at 18:22
  • If you want to write a C# Windows Forms app, use the IDE to create one. Your `Main` function will be in Program.cs, and then it will instantiate an instance of a Form (typically, a class named `Form1`) and then call `Application.Run`, which will spin up an instance of your Form1 class. After that, you have an event driven UI app. Drop a button control on form in the designer. Double-click the button and you will be taken to a newly generated button click handler. Write some code there. But, you have no console – Flydog57 Mar 24 '21 at 18:24

1 Answers1

-1

You started a form, therefore the way intended to interact with users is the form itself, messageboxes are for error or important notifications. The console is an admin tool to look into stuff behind the scenes.