我有一个基本的WinForm,可以在Load事件上加载一些数据 有一个尝试捕获和捕获我有以下代码:
BeginInvoke(new MethodInvoker(Close));
问题在于继承的形式"加载"事件仍然被调用。
我也不能打电话给#34; Invoke"因为我收到的错误是"关闭"在做" CreateHandle"。时,不能调用
甚至包括这个" this.IsHandleCreated"没有用。
如何在基础中出现错误时停止加载继承的表单并关闭继承的表单"加载"事件
更新代码更新
我认为上面列出了足够的信息来解释这个问题,但我想它需要更多的"例如"代码,所以这里......
这是基本形式
public partial class BaseForm : Form
{
public BaseForm()
{
InitializeComponent();
}
private void BaseForm_Load(object sender, EventArgs e)
{
try
{
// only run this code in RunTime
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
// load some data
LoadData();
}
}
catch (Exception ex)
{
// handle the exception and tell the user something BUT don't kill the app... a THROW here could kill the app
HandleException(ex);
// since we are loading the form we need to exit the form if there is an error loading.
BeginInvoke(new MethodInvoker(Close)); // can't close a form on load unless using begin invoke
}
}
}
这里是基础形式的测试形式
public partial class TestForm : BaseForm
{
public TestForm()
{
InitializeComponent();
}
private void TestForm_Load(object sender, EventArgs e)
{
// do some work BUT only if the BASE form loaded correctly
DoSomething();
}
}
答案 0 :(得分:1)
来自" Hans Passant"在这里链接Form_Load() 'event' or Override OnLoad()
我正在使用" OnLoad"基本形式的事件,以阻止"加载"加载时基本表单中存在异常时继承表单的事件。
这是基本形式
public partial class BaseForm : Form
{
public BaseForm()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
try
{
// only run this code in RunTime
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
// load some data
LoadData();
}
// only call the OnLoad event if there is no exception when loading the data of the base form
base.OnLoad(e);
}
catch (Exception ex)
{
// handle the exception and tell the user something BUT don't kill the app... a THROW here could kill the app
HandleException(ex);
// close the forms
this.Close();
}
}
private void BaseForm_Load(object sender, EventArgs e)
{
// NOTE: any exception handled here will still cause the inherited forms Load event to fire
}
}
答案 1 :(得分:0)
避免在Load事件中调用函数。请尝试使用Shown事件。