1

I am trying to test a redirection code that someone is helping me with and it is giving me two cs0120 errors. The first on an integer variable and the second on a textbox. I am new to coding in general and am teaching myself C#. If someone could explain to me what this error means and why I am getting it, that would be great as I see nothing wrong with it and based on other projects I have made it appears to be correct. The errors are all the way at the bottom but I want to put the rest of my code for this just so you have the whole picture even though you probably don't need it.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RedirectRunningTest
{
public partial class Test1 : Form
{
    int instId;

    [DllImport("kernel32.dll")]
    private extern static IntPtr GetStdHandle(int nStdHandle);

    [DllImport("kernel32.dll")]
    static extern bool ReadConsoleOutputCharacter(IntPtr hConsoleOutput,
      [Out] StringBuilder lpCharacter, uint nLength, COORD dwReadCoord,
      out uint lpNumberOfCharsRead);

    [DllImport("kernel32.dll")]
    static extern bool FreeConsole();
    [DllImport("kernel32.dll")]
    static extern bool AttachConsole(int dwProcessId);

    [DllImport("kernel32.dll")]
    static extern bool GetConsoleScreenBufferInfo(
        IntPtr hConsoleOutput,
        out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
    );

    [StructLayout(LayoutKind.Sequential)]
    struct COORD
    {
        public short X;
        public short Y;
    }

    [StructLayout(LayoutKind.Sequential)]
    struct CONSOLE_SCREEN_BUFFER_INFO
    {

        public COORD dwSize;
        public COORD dwCursorPosition;
        public short wAttributes;
        public SMALL_RECT srWindow;
        public COORD dwMaximumWindowSize;

    }

    [StructLayout(LayoutKind.Sequential)]
    struct SMALL_RECT
    {

        public short Left;
        public short Top;
        public short Right;
        public short Bottom;

    }

    const int STD_OUTPUT_HANDLE = -11;
    const Int64 INVALID_HANDLE_VALUE = -1;

    public Test1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bool started = false;
        var p = new Process();
        p.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";

        started = p.Start();

        instId = p.Id;
    }
    private static string ReadALineOfConsoleOutput(IntPtr stdout, ref short currentPosition)
    {

        if (stdout.ToInt32() == INVALID_HANDLE_VALUE)
            throw new Win32Exception();

        //Get Console Info
        if (!GetConsoleScreenBufferInfo(stdout, out CONSOLE_SCREEN_BUFFER_INFO outInfo))
            throw new Win32Exception();

        //Gets Console Output Line Size
        short lineSize = outInfo.dwSize.X;

        //Calculates Number of Lines to be read
        uint numberofLinesToRead = (uint)(outInfo.dwCursorPosition.Y - currentPosition);

        if (numberofLinesToRead < 1) return null;

        //total characters to be read
        uint nLength = (uint)lineSize * numberofLinesToRead;

        StringBuilder lpCharacter = new StringBuilder((int)nLength);

        // read from the first character of the first line (0, 0).
        COORD dwReadCoord;
        dwReadCoord.X = 0;
        dwReadCoord.Y = currentPosition;


        if (!ReadConsoleOutputCharacter(stdout, lpCharacter, nLength, dwReadCoord, out uint lpNumberOfCharsRead))
            throw new Win32Exception();

        currentPosition = outInfo.dwCursorPosition.Y;

        return lpCharacter.ToString();
    }

    public static async Task Main()
    {
        var processId = instId; //CS0120
        if (!FreeConsole()) return;
        if (!AttachConsole(processId)) return;

        IntPtr stdout = GetStdHandle(STD_OUTPUT_HANDLE);
        short currentPosition = 0;

        while (true)
        {
            var r1 = ReadALineOfConsoleOutput(stdout, ref currentPosition);
            if (r1 != null)
                txtConsole.Text = r1; //CS0120
        }
    }
}
}
Jay
  • 3,276
  • 1
  • 28
  • 38
Matt Lynch
  • 155
  • 1
  • 7

2 Answers2

2

If you examine both lines where you get the error, you are accessing an instance object within a static method. This is the cause of error.

In following lines, instId is a non-static variable, so is txtConsole object, both of which is being accessed from a Static Method

 var processId = instId; //CS0120

 txtConsole.Text = r1; //CS0120
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51
1

Your accessing instance variables from a static context.

You should declare a staic method which takes the instance as a parameter that can be worked with.

E.g. add a Test1 as a parameter to the static functions and access the properties of Test1 through the static function.

Another way would be to define an extension method for Test1 using a static class.

Let me know if you need more of an example and I'll make an edit.

See also CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

Jay
  • 3,276
  • 1
  • 28
  • 38