-1

I want to display all modules loaded into a specified process. I used this code and it works:

Process myProcess = new Process();
        myProcess.StartInfo.FileName = "";
        myProcess.StartInfo.WorkingDirectory = "";
        myProcess.Start();
        ProcessModule myProcessModule;
        ProcessModuleCollection myProcessModuleCollection = myProcess.Modules;
        for (int i = 0; i < myProcessModuleCollection.Count; i++)
        {
            myProcessModule = myProcessModuleCollection[i];
            MessageBox.Show(myProcessModule.ModuleName);
        }

But I want to display the modules after a button click, so I did this:

public Process myProcess;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Process myProcess = new Process();
        myProcess.StartInfo.FileName = "";
        myProcess.StartInfo.WorkingDirectory = "";
        myProcess.Start();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        ProcessModule myProcessModule;
        ProcessModuleCollection myProcessModuleCollection = myProcess.Modules;
        for (int i = 0; i < myProcessModuleCollection.Count; i++)
        {
            myProcessModule = myProcessModuleCollection[i];
            MessageBox.Show(myProcessModule.ModuleName);
        }
    }

But it throws me an error "Object reference not set to an instance of an object" for this line:

ProcessModuleCollection myProcessModuleCollection = myProcess.Modules;

I searched for an answer on the internet, tryed everything what could I think of, but it just won't work. I also searched for the error I get and I found out that the program probably thinks that the myProcess.Modules is null, but that doesn't help me either.

Nicolas Cage
  • 33
  • 1
  • 9

1 Answers1

1

myProcess in button1_Click is a local variable.
The field in your class is still null.

You need to remove the variable declaration.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Well, it will probably sound dumb to you, but anyways. Do you mean I have to make myProcess a global variable? Because I already did that in my code. If you mean something else, could you please tell me what? Thanks. – Nicolas Cage Jan 04 '15 at 17:08
  • You have a "global" variable (actually a field in your class), but you're never using it. You are making a local variable in the first function. Don't do that. – SLaks Jan 04 '15 at 17:12
  • Thank you, I finally understand. Looks like I still don't know some basics of C#. :D – Nicolas Cage Jan 04 '15 at 17:26