afaolek afaolek - 2 months ago 10
C# Question

Detect when new display is connected

I'm writing an application that requires two displays: one for the control panel, the other for the output. What I have is this: if there's only one display, the application shows both forms on it but if there are two, the output form goes to the other.
The problem is that this only happens when the application is started. In other words, if the application is already running before the second display is connected, nothing happens unless the user sends the output to the new display manually (assuming they know how to do it).
What I want is that when a new display is connected, the output form is automatically sent to it even while the application is running. I think it has to do with polling a port in a thread but I don't know how to do it. Can anyone help with how to do it? If there is a better solution, I'll gladly welcome it.

(I would have provided some part of the code but I'm typing this from a phone)

Answer

Lookie here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.wndproc.aspx

There's an example which should help you. Try something like this:

protected override void WndProc(ref Message m) 
    {
        const uint WM_DISPLAYCHANGE = 0x007e;

        // Listen for operating system messages. 
        switch (m.Msg)
        {
            case WM_DISPLAYCHANGE:

                // The WParam value is the new bit depth
                uint width = (uint)(m.LParam & 0xffff);
                uint height = (uint)(m.LParam >> 16);
                break;                
        }
        base.WndProc(ref m);
    }