SendKeys.Send NullReferenceException

Mat*_*lko 3 .net vb.net .net-4.0 sendkeys winforms

我正在尝试将密钥发送到我的表单上的控件.但我得到一个NullReferenceException,我不知道为什么.代码基本上是基本的:

Private Sub Button19_Click(sender As System.Object, e As System.EventArgs) Handles Button19.Click
    DateTimePicker2.Focus() 'commenting out this line has no effect
    SendKeys.Send("{F4}") 'error thrown on this line
End Sub
Run Code Online (Sandbox Code Playgroud)

报告的错误是object reference not set to an instance of an object,但是Send是一个共享方法,因此并不需要一个实例.

奇怪的是,如果我忽略错误它工作正常,F4传递给控件.我知道sendkeys和UAC存在问题,但我认为这已经解决了(我使用的是4.0框架)

rok*_*ken 6

该调用不会抛出异常,异常会在SendKeys.LoadSendMethodFromConfig()中引发并在内部处理(因此,如果你在该调用周围放置一个try/catch,你会发现你的用户代码中没有发现异常) .

您在调试器中看到它,因为您将异常设置为在抛出的任何异常时中断,无论它发生在何处或是否已被处理.

我建议转到工具>选项>调试,然后选中"启用我的代码"旁边的框.

以下是抛出异常的方法.请注意,它故意吞下所有异常:

    private static void LoadSendMethodFromConfig()
    { 
        if (!sendMethod.HasValue) 
        {
            sendMethod = SendMethodTypes.Default; 

            try
            {
                // read SendKeys value from config file, not case sensitive 
                string value = System.Configuration.ConfigurationManager.AppSettings.Get("SendKeys");

                if (value.Equals("JournalHook", StringComparison.OrdinalIgnoreCase)) 
                    sendMethod = SendMethodTypes.JournalHook;
                else if (value.Equals("SendInput", StringComparison.OrdinalIgnoreCase)) 
                    sendMethod = SendMethodTypes.SendInput;
            }
            catch {} // ignore any exceptions to keep existing SendKeys behavior
        } 
    }
Run Code Online (Sandbox Code Playgroud)