系统级编程最后一周的实验,一共5个Practice,因为网上没有相关的解答,我给出自己的解答,有兴趣的可以参考参考,有误的可以发送我的邮箱doglikejie@163.com交流
这是ppt的题目要求
我分析之后给出我的源代码
Practice1
第一题是在鼠标点击位置显示时间
我使用了以下重要函数来实现这一功能
GetLocalTime(),这个函数的使用,我先定义了一个SYSTEMTIME类型的变量systime,然后GetLocalTime(&systime);这一行代码把本地时间储存在systime变量里。
然后很重要的一个函数wsprintf(),为什么我这里使用wsprintf函数而不是老师给的sprintf函数,因为我在vs2017环境下编译意外的发现sprintf函数无法被识别,具体原因我也不知道,所以就用了wsprintf函数代替。
wsprintf(str, "[%d年%d月%d日%d时%d分%d秒] ",
systime.wYear, systime.wMonth, systime.wDay,
systime.wHour, systime.wMinute, systime.wSecond);
因为windows编程没有printf这种函数,所以我用wsprintf函数的目的是为了将时间保存为字符串便于打印。我们利用systime.wYear等进一步确定精确的年月日时分秒。
x = LOWORD(lParam);
y = HIWORD(lParam);
这两行分别保存横坐标和纵坐标,关于如何保存鼠标的问题,我查阅网上发现不同的解法,我这里偷懒直接int两个变量x,y保存,网上的通解应该是POINT 一个变量,然后通过变量.x,变量.来储存横纵坐标,这两种方法的优劣我还没思考过。
hdc = GetDC(hwnd);
//输出字符串
TextOut(hdc, x, y, str, strlen(str));
ReleaseDC(hwnd, hdc);
GetDC()和ReleaseDC()必须成对出现,GetDC之后必须释放掉。TextOut负责打印字符串,参数的用法可以查阅msdn。
#include <windows.h>
LRESULT CALLBACK WndProc (HWND,UINT,WPARAM,LPARAM) ;
int WINAPI WinMain (HINSTANCE hInstance,HINSTANCE hPrevInstance,
PSTR szCmdLine,int iCmdShow)
{
static TCHAR szAppName[] =TEXT ("HelloWin") ;
HWND hwnd ;
MSG msg ;
WNDCLASS wndclass ;
wndclass.style = CS_HREDRAW |CS_VREDRAW ;
wndclass.lpfnWndProc = WndProc ;
wndclass.cbClsExtra = 0 ;
wndclass.cbWndExtra = 0 ;
wndclass.hInstance = hInstance ;
wndclass.hIcon = LoadIcon (NULL,IDI_APPLICATION) ;
wndclass.hCursor = LoadCursor (NULL,IDC_ARROW) ;
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName = NULL ;
wndclass.lpszClassName = szAppName ;
if (!RegisterClass (&wndclass))
{
MessageBox (NULL,TEXT ("This program requires Windows NT!"),
szAppName, MB_ICONERROR) ;
return 0 ;
}
hwnd = CreateWindow (szAppName, // window class name
TEXT ("The Hello Program"),// window caption
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // initial x position
CW_USEDEFAULT, // initial y position
CW_USEDEFAULT, // initial x size
CW_USEDEFAULT, // initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle