// Delphi 下調用Windows API 創建窗體. // // 模板-------BY Hottey 2004-4-13-0:18 // // 作者網站:http://asp.itdrp.com/hottey // program delphi;
uses windows, messages;
const hellostr='Hello World!';
{$R delphi.res}
//窗口消息處理函數. function MyWinProc(hWnd:THandle;uMsg:UINT;wParam,lParam:Cardinal):Cardinal;exp ort;stdcall;
var hdca,hdcb:THandle; //設備描述表句柄. rect:TRect; //矩形結構. font:HFont; ps:TPaintStruct; //繪圖結構. begin result:=0; case uMsg of WM_PAINT: begin hdca:=BeginPaint(hWnd,ps); SetBkMode(hdca, Transparent); SetBkColor(hdca,GetBkColor(hdca)); GetClientRect(hWnd,rect); //獲取窗口客戶區的尺寸. DrawText(hdca,Pchar(hellostr),-1,rect,DT_SINGLELINE or DT_CENTER or DT _VCENTER); // TextOut(hdc,100,40,hellostr,Length(hellostr)); EndPaint(hWnd,ps); end; WM_CREATE: begin hdcb := GetDC(hWnd); font := CreateFont(45, 0, 0, 0, FW_normal, 0, 0, 0, ansi_charset, out _default_precis, clip_default_precis, default_quality, 34, PChar('Arial')); SelectObject(hdcb, font); ReleaseDC(hWnd, hdcb); end; WM_DESTROY: PostQuitMessage(0) else //使用缺省的窗口消息處理函數. result:=DefWindowProc(hWnd,uMsg,wParam,lParam); end; end;
//主程序開始.
var Msg :TMsg; //消息結構. hWnd,hInst :THandle; //Windows 窗口句柄. WinClass :TWndClassEx; //Windows 窗口類結構. begin hInst:=GetModuleHandle(nil); // get the application instance WinClass.cbSize:=SizeOf(TWndClassEx); WinClass.lpszClassName:='MyWindow'; //類名. WinClass.style:=CS_HREDRAW or CS_VREDRAW or CS_OWNDC; WinClass.hInstance:=hInst; //程序的實例句柄. //設置窗口消息處理函數. WinClass.lpfnWndProc:=@MyWinProc; //窗口過程. WinClass.cbClsExtra:=0; //以下兩個域用于在類結構和Window s內部保存的窗口結構 WinClass.cbWndExtra:=0; //中預留一些額外空間. WinClass.hIcon:=LoadIcon(hInstance,MakeIntResource('MAINICON')); WinClass.hIconsm:=LoadIcon(hInstance,MakeIntResource('MAINICON')); WinClass.hCursor:=LoadCursor(0,IDC_Arrow); //GetStockObject 獲取一個圖形對象,在這里是獲取繪制窗口背景的刷子,返回一個白色刷 子的句柄. WinClass.hbrBackground:=HBRUSH(GetStockObject(white_Brush)); WinClass.lpszMenuName:=nil; //指定窗口類菜單.
//向Windows 注冊窗口類. if RegisterClassEx(WinClass)=0 then begin MessageBox(0,'Registeration Error!','SDK/API',MB_OK); Exit; end;
//建立窗口對象. hWnd:=CreateWindowEx( WS_EX_OVERLAPPEDWINDOW, //擴展的窗口風格. WinClass.lpszClassName, //類名. 'Hello Window', //窗口標題. WS_OVERLAPPEDWINDOW, //窗口風格. CW_USEDEFAULT, //窗口左上角相對于屏幕 左上角的初始位置x. 0, //....右y. CW_USEDEFAULT, //窗口寬度x. 0, //窗口高度y. 0, //父窗口句柄. 0, //窗口菜單句柄. hInst, //程序實例句柄. nil); //創建參數指針. if hWnd<>0 then begin ShowWindow(hWnd,SW_SHOWNORMAL); //顯示窗口. UpdateWindow(hWnd); //指示窗口刷新自己. SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE + SWP_NOSIZE);
end else MessageBox(0,'Window not Created!','SDK/API',MB_OK);
//主消息循環程序. while GetMessage(Msg,0,0,0) do begin TranslateMessage(Msg); //轉換某些鍵盤消息. DispatchMessage(Msg); //將消息發送給窗口過程. end; end.
>其實Windows 編程是每個學寫程序的人都要掌握的,學Delphi時也最好能先學習Windos編 程(最少要知道).以上代碼雖說不如在Delphi中直接來個New->Form來的快,但它能告訴你本 質的東西.能讓你更好的了解消息循環以及其他.而這些正是讓New出來的窗體給掩蓋的部分 . >注:以上代碼是我從Windows 程序設計上通過C++語法直譯過來的(),測試后沒有問題.若我 的注解有什么錯誤的地方,請各位指正!^_^ hottey 于2004-5-19 作者網站:http://asp.itdrp.com/hottey (附例程)
|