![](/img/trans.png)
[英]Why Class keeps throwing 'The type initializer for 'MyClass' threw an exception.'
[英]How to debug “Type initializer for 'WindowsFormsAutoClick.Form1' threw an exception.”?
我正在嘗試添加新的Dictionary值並將新的用戶控件添加到Flow布局。 但是按下添加控件按鈕會拋出一個初始化異常,並帶有內部異常,例如“已添加密鑰”。 我不知道完整的異常,因為我在查找如何打開通常在Visual Studio中顯示的彈出錯誤時遇到了困難。
已設置循環以檢查密鑰是否已添加到字典中,如果是,則更改密鑰(如代碼blocK中所示)。 還嘗試清除流布局控件列表。 (沒有更改錯誤)
函數被拋出錯誤:
/// <summary>
/// Create a new key propertie set.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonAddKey_Click(object sender, EventArgs e)
{
// Create new UI key component in the flow layout.
KeyPropertiesCtrl inputKeyCtrl = new KeyPropertiesCtrl();
flowLayoutKeys.Controls.Add(inputKeyCtrl);
Console.WriteLine("inputKeyCtrl " + inputKeyCtrl.Name + " parent " + inputKeyCtrl.Parent.Name);
// Create new data input key.
CustomInputKey newKey = new CustomInputKey();
newKey.Activation.InputKey = new Interception();
Console.WriteLine("newKey " + newKey.Activation.InputKey);
// Get a key binding from the user.
try
{
Form1.Context = InterceptionDriver.CreateContext();
InterceptionDriver.SetFilter(Form1.Context, InterceptionDriver.IsKeyboard, (Int32)KeyboardFilterMode.All);
InterceptionDriver.SetFilter(Form1.Context, InterceptionDriver.IsMouse, (Int32)MouseFilterMode.All);
Form1.InterceptOnce(Form1.Context, out newKey.Activation.InputKey.DeviceId, out newKey.Activation.InputKey.TheStroke);
InterceptionDriver.DestroyContext(Form1.Context);
// Change the key bind in UI text.
if (newKey.Activation.InputKey.TheStroke.Key.State != 0)
inputKeyCtrl.button1.Text = newKey.Activation.InputKey.TheStroke.Key.Code.ToString();
else
inputKeyCtrl.button1.Text = newKey.Activation.InputKey.TheStroke.Mouse.State.ToString();
}
catch (Exception excp)
{ Console.WriteLine(excp); }
// Set the key bind in data list.
string name = inputKeyCtrl.Name;
byte attempts = 0;
while (Form1.CurrentSelections.SelectedPreset.GetCustomKeys.ContainsKey(name))
{
if (attempts > 50)
{
break;
}
attempts++;
name += attempts;
}
Console.WriteLine(this.Name + " name Attempts " + attempts + " name " + name);
if (attempts < 50)
Form1.CurrentSelections.SelectedPreset.AddKey(Form1.CurrentSelections.SelectedPresetName, name, newKey);
}
所以我真正期望的是在按下按鈕控制之后。 它在流布局中創建一個新的用戶控件,然后當它到達InterceptOnce()函數時凍結應用程序,因為它會等待我按下輸入來綁定該輸入。 最后存儲新的密鑰綁定並將字典保存到文件中。
但它在while(Form1.CurrentSelections ...){}的行上引發異常“key has has added”,之后我添加了while循環和try {}異常拋出Form1.Context = InterceptionDriver。的createContext(); 這很奇怪,因為使用try {} catch(Exception excp){}它不會拋出異常。 我認為異常與新的CustomInputKey()有關; 並且不知道為什么......
錯誤: 截圖
初始化程序錯誤信息也顯示在類[設計]中。 拋出異常會使變量非靜態移動,這有助於我找到異常的原因。
事實證明,我在控制組件的初始化階段將值分配給尚未創建的變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.