Mono WinForms with sudo

Apr 21, 2015

When hacking away on my C#/mono projects on the Raspberry Pi, I find it handy to have a WinForms app to help debug/diagnose various conditions by having various knobs and dials I can tweak and experiment with.

WinForms on the Raspberry Pi

When using the i2c bus, the mono is required to run elevated with sudo. sudo works fine for console apps, but when running the WinForms app I got this error

Unhandled Exception:
System.TypeInitializationException: An exception was thrown by the type initializer for System.Windows.Forms.XplatUI ---> System.ArgumentNullException: Could not open display (X-Server required. Check your DISPLAY environment variable)
Parameter name: Display

This presumably happens because the application is running under a different user context and it can't find the various UI environment variables.

I eventually found the answer in gksudo which is what one needs to use when wanting to run a GUI app elevated in X-Windows. So instead of

sudo mono

I needed

gksudo mono

Or if you are using parallel mono environments:

gksudo -- bash -c 'source; mono'