0

当我第二次打开在运行时创建的表单时,我不断收到错误消息“无法访问已处置的对象”。“对象名称'Form'” 这里是函数的代码。它由 buttonclick 事件调用。我查看了整个网络,发现有类似问题的人,但是我尝试了这些修复,但没有一个有效。不知道如何解决这个问题。VS 高亮显示 frmFavorites.Show();

先感谢您。

public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{        
    frmFavorites.ShowIcon = false;
    frmFavorites.ShowInTaskbar = false;
    frmFavorites.Text = "Bookmarks";
    frmFavorites.Width = 500;
    frmFavorites.Height = 320;
    frmFavorites.Controls.Add(lstFavorites);
    frmFavorites.Controls.Add(btnRemoveFavorite);
    frmFavorites.Controls.Add(btnAddFavorite);
    frmFavorites.Controls.Add(txtCurrentUrl);
    lstFavorites.Width = 484;
    lstFavorites.Height = 245;
    btnRemoveFavorite.Location = new Point(397, 255);
    btnAddFavorite.Location = new Point(8, 255);
    txtCurrentUrl.Location = new Point(110, 255);
    txtCurrentUrl.Size = new Size(265, 20);
    btnAddFavorite.Text = "Add";
    btnRemoveFavorite.Text = "Remove";
    txtCurrentUrl.Text = wbBrowser.Url.ToString();
    btnAddFavorite.Click += new EventHandler(btnAddFavorite_Click);
    btnRemoveFavorite.Click += new EventHandler(btnRemoveFavorite_Click);
    frmFavorites.Load += new EventHandler(frmFavorites_Load);
    frmFavorites.Show();
    frmFavorites.FormClosed += new FormClosedEventHandler(frmFavorites_FormClosed);

    StreamReader reader = new System.IO.StreamReader(@Application.StartupPath + "\\favorites.txt");
    {
        while (!reader.EndOfStream)
        {
            for (int i = 0; i < 4; i++)
            {
                string strListItem = reader.ReadLine();
                if (!String.IsNullOrEmpty(strListItem))
                {
                     lstFavorites.Items.Add(strListItem);
                }
            }
        }
        reader.Close();   
    }        
}

public void btnAddFavorite_Click(object sender, EventArgs e)
{
    lstFavorites.Items.Add(wbBrowser.Url.ToString());
}

public void btnRemoveFavorite_Click(object sender, EventArgs e)
{
    try
    {
        lstFavorites.Items.RemoveAt(lstFavorites.SelectedIndices[0]);
    }
    catch
    {
        MessageBox.Show("You need to select an item", "Error");
    }
}
public void frmFavorites_Load(object sender, EventArgs e)
{       
}

public void frmFavorites_FormClosed(object sender, FormClosedEventArgs e)
{
    StreamWriter writer = new System.IO.StreamWriter(@Application.StartupPath + "\\favorites.txt");
    {
        for (int i = 0; i < lstFavorites.Items.Count; i++)
        {
            writer.WriteLine(lstFavorites.Items[i].ToString());
        }
        writer.Close();
    }
    frmFavorites.Close();
 }
4

2 回答 2

2

试试这个

public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{
  frmFavorites = new Form();

   ....
   ....

}
于 2012-07-10T07:32:57.770 回答
2

您无法重新打开已关闭的表单。当窗体关闭时 (1) 它被释放并且 (2) 底层操作系统窗口句柄被释放。

我想您可能能够获取表单构造函数的内容并将其放入您可以调用以重新打开表单的方法中,但我真的不建议这样做,即使它确实有效。

相反,只需创建表单的一个新实例。

于 2012-07-10T07:44:45.090 回答