【问题标题】:C# code (method) runs when application is closedC# 代码(方法)在应用程序关闭时运行
【发布时间】:2013-04-05 11:35:51
【问题描述】:

我有一个按钮,按下它会关闭当前表单并打开同一类的新表单 - 即它会以原始状态打开一个新表单。

我有另一个具有相同功能的按钮,但是我尝试在代码中调用一个函数,因此当新表单打开时它会运行 importGantt() 表单的一个函数。

我遇到的问题是,当我单击按钮时,它会按预期关闭当前表单并打开一个新表单,但是在我关闭应用程序之前它不会调用 importGantt() 函数。

有什么想法吗?

非常感谢。

private void browseFileToolStripMenuItem_Click(object sender, EventArgs e)
    {
        clearAndImport();
    }

private void clearAndImport()
    {
        this.Hide();
        Dashboard dashboard = new Dashboard();
        dashboard.ShowDialog();
        dashboard.importGantt();
        this.Close();
    }

private void importGantt()
    {
        // Edit Interface
        btnImport.Visible = false;
        dataCapPlan.Visible = true;
        dataMilestones.Visible = true;
        pnlGantt.Visible = true;
        Graphics ganttGraphics = pnlGantt.CreateGraphics();

        // Draw axis


        // Import Files
        fileCapPlan.Title = "Select Capital Plan File";
        fileCapPlan.Filter = "Excel Workbook (.xlsx)|*.xlsx";
        DialogResult resCapPlan = fileCapPlan.ShowDialog();
        if (resCapPlan == DialogResult.OK)
        {
            cnStr = cnStr + fileCapPlan.FileName;
        }
        else
        {
            MessageBox.Show("Error: Unable to import file");
        }
        fileMilestones.Title = "Select Milestones File";
        fileMilestones.Filter = "Excel Workbook (.xlsx)|*.xlsx";
        DialogResult resMilestones = fileMilestones.ShowDialog();
        if (resMilestones == DialogResult.OK)
        {
            cnStr2 = cnStr2 + fileMilestones.FileName;
        }
        else
        {
            MessageBox.Show("Error: Unable to import file");
        }

        // Use OleDb connection to import Excel data
        using (OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + cnStr + ";Extended Properties=" + "'EXCEL 12.0 Xml;HDR=YES'"))
        {
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(sqlSelectAll, cn))
            {
                adapter.Fill(dtCapPlan);
                dataCapPlan.DataSource = dtCapPlan;
                dataCapPlan.AutoResizeColumns();
            }
        }
        using (OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + cnStr2 + ";Extended Properties=" + "'EXCEL 12.0 Xml;HDR=YES'"))
        {
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(sqlSelectAll, cn))
            {
                adapter.Fill(dtMilestones);
                dataMilestones.DataSource = dtMilestones;
                dataMilestones.AutoResizeColumns();
            }
        }

        // Draw Gantt Chart
        foreach (DataRow rowCapPlan in dtCapPlan.Rows)
        {
            id = rowCapPlan["Program ID"].ToString();

            foreach (DataRow rowMilestone in dtMilestones.Rows)
            {
                if (id == rowMilestone["Program ID"].ToString())
                {
                    // calculate space in days from todays date and the milestone date
                    msDate = Convert.ToDateTime(rowMilestone["Milestone Date"]);
                    msTimespan = msDate - calDate;
                    msIntDate = (int)msTimespan.TotalDays + 1;
                    tTimespan = tDate - calDate;
                    tIntDate = (int)tTimespan.TotalDays + 1;
                    ganttPlotSpace = msIntDate - tIntDate;

                    // Draw each milestone or gateway which is not yet complete
                    if (rowMilestone["% Complete"].ToString() != "100")
                    {
                        taskname = rowMilestone["Task Name"].ToString();
                        if (taskname == "Gateway 1" || taskname == "Gateway 2" || taskname == "Gateway 3" || taskname == "Gateway 4" || taskname == "Gateway 5")
                        {
                            Rectangle gw = new Rectangle(startx + ganttPlotSpace, starty - 4, 2, 11);
                            ganttGraphics.DrawRectangle(gwPen, gw);
                            ganttGraphics.FillRectangle(gwBrush, gw);
                        }
                        else
                        {
                            Rectangle ms = new Rectangle(startx + ganttPlotSpace + 1, starty, 2, 2);
                            ganttGraphics.DrawRectangle(msPen, ms);
                            ganttGraphics.FillRectangle(msBrush, ms);
                        }
                        ganttGraphics.DrawLine(linePen, startx - 10, starty - 11, pnlGantt.Right, starty - 11);
                    }
                }
            }
            starty = starty + 22;
        }
        ganttGraphics.DrawLine(linePen, startx - 10, starty + 11, pnlGantt.Right, starty + 11);
    }

带有甘特图的图像

clearAndImport 方法后的图像(由用户修复)


根据 Brij 指导:

好的,在指导下这几乎可以工作了,现在代码如下......

现在这会打开新表单并运行导入方法,但是,它似乎是在循环运行它。 IE。它运行成功显示甘特图,但随后尝试再次运行导入甘特图方法。

bool clear;



public Dashboard(bool clear = false)
    {
        InitializeComponent();
        dataCapPlan.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataCapPlan_ColumnHeaderMouseClick);

        this.clear = clear;
        this.Load += new EventHandler(Dashboard_Load);
    }
    private void Dashboard_Load(object sender, EventArgs e)
    {
        if (this.clear)
        {
            this.importGantt();
        }
    }

// Clear and import method
    private void clearAndImport()
    {
        this.Hide();
        Dashboard dashboard = new Dashboard();
        dashboard.clear = true;
        dashboard.ShowDialog();
        this.Close();
    }

【问题讨论】:

  • 为什么关闭并重新打开同一个表单?为什么不更新一下?
  • 嗨@Nolonar,感谢您的回复。我最初是这样尝试的。但是我遇到了很多错误;清除数据表、面板,然后尝试使用 oledb 重新导入 excel 数据。部分功能是将表单清除回原始状态,因此希望以这种方式使用它。当函数运行时,表单界面也会发生变化,所以最简单的方法就是恢复正常(我假设!)。

标签: c# winforms methods close-application


【解决方案1】:

我认为您所指的方法如下:

private void clearAndImport()
{
        this.Hide();
        Dashboard dashboard = new Dashboard();
        dashboard.ShowDialog();
        dashboard.importGantt();
        this.Close();
}

您正在呼叫dashboard.ShowDialog()。因此,在您关闭“仪表板”表单之前,不会调用下一行代码 (dashboard.importGantt())。我建议你在构造函数中调用importGantt(),或者在仪表板表单的加载事件中调用。您也可以通过将dashboard.importGantt() 移动到dashboard.ShowDialog() 上方来更改代码顺序。


根据您的评论,我建议修改Dashboard 类的构造函数以接受布尔参数并使其可选(默认为false)。如果通过了 true,则只调用 importGantt()。所以它会是这样的:

public Dashboard(bool clear = false)
{
   InitializeComponent();
   if(clear)
   {
       this.importGantt();
   }
}

clearAndImport() 方法会是这样的:

private void clearAndImport()
{
        this.Hide();
        Dashboard dashboard = new Dashboard(true);
        dashboard.ShowDialog();
        this.Close();
}

根据我上次的评论,试试这个:

bool clear = false;
public Dashboard(bool clear = false)
{
        InitializeComponent();
        this.clear = clear;
        this.Load += new EventHandler(Dashboard_Load);
}

void Dashboard_Load(object sender, EventArgs)
{
    if(this.clear)
    {
       this.importGantt();
    }
}

【讨论】:

  • 感谢您的回复,绝对有道理!我唯一的问题是我不希望在应用程序表单打开时调用该函数,仅在用户想要清除仪表板并重新导入的情况下。目前用户可以清除仪表板(关闭并打开新表单),然后在新表单中使用导入按钮作为单独的实体,但我想将它们组合成一个功能。
  • 查看以上答案的进一步补充。
  • 太棒了,非常感谢。这部分有效......由于某种原因它没有完成该方法的面板图形绘制部分。如果我单独调用该方法,我将在该方法的作用问题中添加一张图片,并为 clear 和 import 方法添加另一张图片。
  • 试试这个:将“clear”参数的值保存在Dashboard类的局部变量中,并将if(clear) { this.importGantt(); }代码移动到DashBoard类的Load事件中。
  • 嗨,再次感谢。不知道我做对了。 ` public Dashboard() { InitializeComponent(); dataCapPlan.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataCapPlan_ColumnHeaderMouseClick); if (clear) { this.importGantt(); } }`
【解决方案2】:

尝试dashboard.Show(); 而不是dashboard.ShowDialog();

using (var dashboard = new Dashboard())
{
    dashboard.Show(); // Show the form
    dashboard.importGantt(); // Call
    dashboard.Close(); // Close it when you're done...
} 

【讨论】:

  • 感谢您的回复,这可行,但是现在应用程序在新表单调用该函数后关闭。
  • U 可以在您的表单中提供一个计时器来关闭它,或者将一个委托传递给表单以在 Show 上运行您的方法,之后它可以自行关闭。
  • @NickB6 - 由于您想要的方式,您遇到了问题。如果需要,正确的方法是调用对表单控件的更改。你的代码有缺陷,实际上是按照它的程序运行的。
  • 嗨@Ramhound,感谢您的回复。是的,我确实理解这一点,根据我的 OP 上对 q 的评论,我尝试刷新所有表单控件,但是遇到了很多错误。关于如何刷新两个数据表(在 datagridview 中查看)和图形面板的任何建议,请参见 OP 中的图片?我需要删除/使它们无效并创建新实例吗?我尝试使用控件清除方法,但这不起作用。
猜你喜欢
  • 1970-01-01
  • 2020-08-31
  • 2022-01-20
  • 2022-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多