Registering a custom win32 window class from c#

后端 未结 4 1381
无人及你
无人及你 2020-12-05 12:12

I have a new application written in WPF that needs to support an old API that allows it to receive a message that has been posted to a hidden window. Typically another appl

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 12:41

    I'd like to comment the answer of morechilli:

    public CustomWindow(string class_name){
    
        if (class_name == null) throw new System.Exception("class_name is null");
        if (class_name == String.Empty) throw new System.Exception("class_name is empty");
    
        // Create WNDCLASS
        WNDCLASS wind_class = new WNDCLASS();
        wind_class.lpszClassName = class_name;
        wind_class.lpfnWndProc = CustomWndProc;
    
        UInt16 class_atom = RegisterClassW(ref wind_class);
    
        int last_error = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
    
        if (class_atom == 0 && last_error != ERROR_CLASS_ALREADY_EXISTS) {
            throw new System.Exception("Could not register window class");
        }
    
        // Create window
        m_hwnd = CreateWindowExW(
            0,
            class_name,
            String.Empty,
            0,
            0,
            0,
            0,
            0,
            IntPtr.Zero,
            IntPtr.Zero,
            IntPtr.Zero,
            IntPtr.Zero
        );
    }
    

    In the constructor I copied above is slight error: The WNDCLASS instance is created, but not saved. It will eventually be garbage collected. But the WNDCLASS holds the WndProc delegate. This results in an error as soon as WNDCLASS is garbage collected. The instance of WNDCLASS should be hold in a member variable until the window is destroyed.

提交回复
热议问题