我有以下代码,当表单失去焦点时(当点击另一个程序时)抛出NullReference异常:
namespace MyProg
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
Mouse Mouse = new Mouse();
Thread Thread = new Thread(new ThreadStart(Mouse.Hook));
Thread.Start();
}
internal static bool IsTransparent = true;
internal static void TransparentForm()
{
Main.ActiveForm.TransparencyKey = (Main.IsTransparent ? Color.Firebrick : Color.AliceBlue);
}
}
public class Mouse
{
public void Hook()
{
while(true)
{
if(Screen.AllScreens.Length > 1)
{
if(Cursor.Position.X < 1300)
{
Main.IsTransparent = true;
Main.ActiveForm.Invoke(new MethodInvoker(Main.TransparentForm));
}
// .....
}
}
}
}
如何消除Main.ActiveForm
?
答案 0 :(得分:0)
根据Form.ActiveForm
的规范,如果程序中没有任何表格处于活动状态,则应该返回null(如果另一个程序具有焦点,则会出现这种情况)。
尝试将Main.ActiveForm.Invoke
中的if
包裹在Main.ActiveForm
内,以检查{{1}}是否为空。
答案 1 :(得分:0)
根据您的代码风格直接回答您的问题:
Thread Thread = new Thread(new ParameterizedThreadStart(Mouse.Hook));
Thread.Start(this);
然后
public void Hook(object mainObject)
{
Main form = (Main)mainObject;
while(true)
{
// ...