はじめに
ctypesパッケージを使ってWindows APIを呼び出すサンプルとしてウィンドウを表示してみた。
ソース
winapp.py
from ctypes import *
from ctypes.wintypes import *
gdi32 = windll.gdi32
kernel32 = windll.kernel32
user32 = windll.user32
CS_HREDRAW = 0x0002
CS_VREDRAW = 0x0001
IDC_ARROW = 32512
COLOR_WINDOW = 5
WS_OVERLAPPEDWINDOW = 0x00CF0000
CW_USEDEFAULT = 0x80000000
SW_SHOWDEFAULT = 10
WM_DESTROY = 0x0002
WM_PAINT = 0x000F
WNDPROC = WINFUNCTYPE(LONG, HWND, UINT, WPARAM, LPARAM)
class WNDCLASSEXW(Structure):
_fields_ = [
("cbSize", UINT),
("style", UINT),
("lpfnWndProc", WNDPROC),
("cbClsExtra", c_int),
("cbWndExtra", c_int),
("hInstance", HINSTANCE),
("hIcon", HICON),
("hCursor", HANDLE),
("hbrBackground", HBRUSH),
("lpszMenuName", LPCWSTR),
("lpszClassName", LPCWSTR),
("hIconSm", HICON),
]
class PAINTSTRUCT(Structure):
_fields_ = [
("hdc", HDC),
("fErase", BOOL),
("rcPaint", RECT),
("fRestore", BOOL),
("fIncUpdate", BOOL),
("rgbReserved", BYTE * 32),
]
def WinMain(hInstance, nShowCmd):
wc = WNDCLASSEXW()
wc.cbSize = sizeof(WNDCLASSEXW)
wc.style = CS_HREDRAW | CS_VREDRAW
wc.lpfnWndProc = WNDPROC(WndProc)
wc.hInstance = hInstance
wc.hCursor = user32.LoadCursorW(None, IDC_ARROW)
wc.hbrBackground = HBRUSH(COLOR_WINDOW + 1)
wc.lpszClassName = "winapp"
ret = user32.RegisterClassExW(wc)
hWnd = user32.CreateWindowExW(
0, "winapp", "winapp",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0,
CW_USEDEFAULT, 0,
None, None, hInstance, None)
user32.ShowWindow(hWnd, nShowCmd)
user32.UpdateWindow(hWnd)
msg = MSG()
while user32.GetMessageW(byref(msg), None, 0, 0):
user32.TranslateMessage(msg)
user32.DispatchMessageW(msg)
return msg.wParam
def WndProc(hWnd, uMsg, wParam, lParam):
if uMsg == WM_DESTROY:
user32.PostQuitMessage(0)
return 0
if uMsg == WM_PAINT:
OnPaint(hWnd)
return 0
return user32.DefWindowProcW(hWnd, uMsg, WPARAM(wParam), LPARAM(lParam))
def OnPaint(hWnd):
ps = PAINTSTRUCT()
hdc = user32.BeginPaint(hWnd, byref(ps))
txt = "hello, world"
gdi32.TextOutW(hdc, 10, 10, txt, len(txt))
user32.EndPaint(hWnd, ps)
hInstance = kernel32.GetModuleHandleW(None)
WinMain(hInstance, SW_SHOWDEFAULT)
実行
py winapp.py