lxn / win

A Windows API wrapper package for the Go Programming Language
Other
1.19k stars 312 forks source link

Window not created but GetLast returns success #104

Closed TotallyGamerJet closed 4 years ago

TotallyGamerJet commented 4 years ago

I'm probably doing something stupid. But I'm trying to replicate this Windows tutorial. But when I run this code RegisterClassEx fails returning 0. Not sure if this helps but it never calls my WndProc function. (I place a Printf on the first line)

 package main

 import (
     "fmt"
     "github.com/lxn/win"
     "golang.org/x/sys/windows"
 )

 func main() {
     className := "SomeFunkyNameHere"

     wc := win.WNDCLASSEX{}

     hInst := win.GetModuleHandle(nil)
     if hInst == 0 {
         panic("GetModuleHandle")
     }

     wc.LpfnWndProc = windows.NewCallback(WndProc)
     wc.HInstance = hInst
     wc.LpszClassName = windows.StringToUTF16Ptr(className)

     if atom := win.RegisterClassEx(&wc); atom == 0 {
         panic("RegisterClassEx")
     }

     hwnd := win.CreateWindowEx(
         0,
         wc.LpszClassName,
         windows.StringToUTF16Ptr("Learn to program"),
         win.WS_OVERLAPPEDWINDOW,
         win.CW_USEDEFAULT, win.CW_USEDEFAULT, win.CW_USEDEFAULT, win.CW_USEDEFAULT,
         0,
             0,
         hInst,
        nil,
     )
     if hwnd == 0 {
         panic(win.GetLastError())
     }

     win.ShowWindow(hwnd, win.SW_SHOW)
     msg := win.MSG{}
     for win.GetMessage(&msg, 0, 0, 0) != 0 {
         win.TranslateMessage(&msg)
         win.DispatchMessage(&msg)
     }
}

 func WndProc(hwnd win.HWND, msg uint32, wParam, lParam uintptr) uintptr {
     switch msg {
     case win.WM_DESTROY:
        win.PostQuitMessage(0)
     case win.WM_PAINT:
          ps := win.PAINTSTRUCT{}
          hdc := win.BeginPaint(hwnd, &ps)
         r := ps.RcPaint
         hrgn := win.CreateRectRgn(r.Left, r.Top, r.Right, r.Bottom)
         win.FillRgn(hdc, hrgn, win.COLOR_WINDOW+1)
         win.EndPaint(hwnd, &ps)
     }
     return win.DefWindowProc(hwnd, msg, wParam, lParam)
 }
TotallyGamerJet commented 4 years ago

SOLUTION Make sure to include the size of the Window Class before registering it wc.CbSize = uint32(unsafe.Sizeof(wc))