Process.Modules 仅在进程启动后立即工作

Process.Modules working only right after start of process

我想显示加载到指定进程的所有模块。我使用了这段代码并且有效:

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);
        }

但是我想在点击按钮后显示模块,所以我这样做了:

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);
        }
    }

但是这行给我一个错误 "Object reference not set to an instance of an object":

ProcessModuleCollection myProcessModuleCollection = myProcess.Modules;

我在互联网上搜索了答案,尝试了所有我能想到的方法,但就是不管用。我还搜索了我得到的错误,我发现该程序可能认为 myProcess.Modules 为空,但这对我也没有帮助。

myProcessbutton1_Click是局部变量。
您的 class 中的字段仍然是 null

您需要删除变量声明。