SendKeys.Send NullReferenceException

.net, .net-4.0, sendkeys, vb.net, winforms

Solution

That call is not throwing an exception, the exception is thrown in the SendKeys.LoadSendMethodFromConfig() and is handled internally (so if you were to put a try/catch around that call you would see no exception is actually caught in your user code).

You're seeing it in the debugger because you have your exceptions set to break on any exception thrown, regardless of where it occurs or if it has been handled.

I suggest going to Tools > Options > Debugging and check the box next to "Enable Just My Code".

Here's what the method throwing the exception looks like. Note that it is swallowing all exceptions on purpose:

    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
        } 
    }

Problem

I am trying to send keys to a control on my form. But I am getting a NullReferenceException and I don't know why. The code is about as basic as it gets: ``` 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 ``` The error reported is `object reference not set to an instance of an object` but `Send` is a shared method so doesn't need an instance. Strangely if I ignore the error it works fine and F4 is passed to the control. I know there was an issue with sendkeys and UAC but I thought this had been solved (I am using 4.0 framework)

Original source