Module 1. Your First Windows Program (Windows)

模块1. 你的第一个Windows程序

In this module, we will write a minimal Windows program. All it does is create and show a blank window. This first program contains about 50 lines of code, not counting blank lines and comments. It will be our starting point; later we'll add graphics, text, user input, and other features.

在这个模块,我们将写一个显示空白窗口的迷你的Windows程序。不计空行跟注释的话这个程序包含50行代码,这是我们步入Windows编程的开端,稍后我们将添加图形、文本、用户输入以及其他的特性。

Screen shot of the example program

示例程序的截图

Here is the complete code for the program:

这里有完整的代码:

#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
// Register the window class.
const wchar_t CLASS_NAME[]  = L"Sample Window Class";
WNDCLASS wc = { };
wc.lpfnWndProc   = WindowProc;
wc.hInstance     = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window.
HWND hwnd = CreateWindowEx(
0,                              // Optional window styles.
CLASS_NAME,                     // Window class
L"Learn to Program Windows",    // Window text
WS_OVERLAPPEDWINDOW,            // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL,       // Parent window
NULL,       // Menu
hInstance,  // Instance handle
NULL        // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
// Run the message loop.
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));
EndPaint(hwnd, &ps);
}
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

You can download the complete Visual Studio project from Windows Hello World Sample.

你可以下载完整的Visual Studio工程:Windows Hello World Sample。

It may be useful to give a brief outline of what this code does. Later topics will examine the code in detail.

对这些代码先做一个简要介绍也许有一定作用,在以后的主题里再详细解读代码。

1.wWinMain is the program entry point. When the program starts, it registers some information about the behavior of the application window. One of the most important items is the address of a function, named WindowProc in this example. This function defines the behavior of the window—its appearance, how it interacts with the user, and so forth.

1.wWinMain是程序的入口点,当程序开始时,一些关于应用程序窗口的信息将被注册,其中最重要的项目是函数地址,也就是例子中的WindowProc。这个函数定义了窗口的行为——他如何显示,如何与用户交互并以此类推。

2.Next, the program creates the window and receives a handle that uniquely identifies the window.

2.下一步,程序创建了窗口并接收一个句柄作为唯一标识。

3.If the window is created successfully, the program enters awhile loop. The program remains in this loop until the user closes the window and exits the application.

3.如果窗口创建成功,程序就进入了while循环,直到用户关闭窗口退出程序。

Notice that the program does not explicitly call the WindowProc function, even though we said this is where most of the application logic is defined. Windows communicates with your program by passing it a series ofmessages. The code inside the while loop drives this process. Each time the program calls theDispatchMessage function, it indirectly causes Windows to invoke the WindowProc function, once for each message.

注意:程序不显式地调用WindowProc函数,虽然我们说这是大部分程序的逻辑定义。Windows通过一系列的messages与你的程序通信。这些代码在while循环里驱动着进程,针对每一条message,程序都调用DispatchMessage函数,这间接引起Windows去调用WindowProc函数。

Creating a Window (Windows)

创建一个窗口

Window Classes

窗口类

window class defines a set of behaviors that several windows might have in common. For example, in a group of buttons, each button has a similar behavior when the user clicks the button. Of course, buttons are not completely identical; each button displays its own text string and has its own screen coordinates. Data that is unique for each window is called instance data.

窗口类定义了数个窗口共同的一组行为,例如,一组按钮,每个按钮在用户点击的时候都有相似的行为。当然,这些按钮不可能都是一模一样的,每个按钮有自己的坐标跟文字,每一个有独特数据的窗口被称之为“数据实例”。

Every window must be associated with a window class, even if your program only ever creates one instance of that class. It is important to understand that a window class is not a "class" in the C++ sense. Rather, it is a data structure used internally by the operating system. Window classes are registered with the system at run time. To register a new window class, start by filling in a WNDCLASS structure:

每一个窗口都必须关联一个窗口类,即使你的程序只创建一个类的实例。要知道一个窗口的类跟C++中类不一样,相反,它是一种在操作系统内部使用的数据结构。窗口类都在运行期中向系统注册过,而注册一个窗口类,是从给WNDCLASS结构体的赋值开始。

    // Register the window class. 注册窗口类
const wchar_t CLASS_NAME[]  = L"Sample Window Class";
WNDCLASS wc = { };
wc.lpfnWndProc   = WindowProc;
wc.hInstance     = hInstance;
wc.lpszClassName = CLASS_NAME;

You must set the following structure members:

你必须设置一下结构体成员:

  • lpfnWndProc is a pointer to an application-defined function called the window procedure or "window proc." The window procedure defines most of the behavior of the window. We'll examine the window procedure in detail later. For now, just treat this as a forward reference.
  • lpfnWndProc是一个已定义的应用程序函数指针,叫做“窗口过程”或者“window proc”。窗口过程定义了大部分窗口动作,之后我们将详细解读“窗口过程”这一概念,现在,仅作为预习;
  • hInstance is the handle to the application instance. Get this value from the hInstance parameter of wWinMain.
  • hInstance是应用程序实例的句柄,从wWinMain的hIntance参数得到这个值;
  • lpszClassName is a string that identifies the window class.
  • lpszClassName是窗口类的字符串标识符

Class names are local to the current process, so the name only needs to be unique within the process. However, the standard Windows controls also have classes. If you use any of those controls, you must pick class names that do not conflict with the control class names. For example, the window class for the button control is named "Button".

类名称局限于当前进程,所以只要在这个进程内保证唯一即可。然而,标准的Windows控件也包含许多类,如果你用了里面的任何一些,都必须保证类名不能冲突,例如作为按钮的窗口类名为“Button”,你就不能再使用这个类名。

The WNDCLASS structure has other members not shown here. You can set them to zero, as shown in this example, or fill them in. The MSDN documentation describes the structure in detail.

在这里WNDCLASS还有其他的结构体成员没有展示出来,你可以就像示例里面一样把他们置零或给他们赋值,MSDN文档描述里面有详细的结构体信息可供查阅。

Next, pass the address of the WNDCLASS structure to the RegisterClass function. This function registers the window class with the operating system.

下一步,通过把WNDCLASS结构体的地址传给RegisterClass函数,把窗口类注册到操作系统。代码如下:

    RegisterClass(&wc);

Creating the Window

创建窗口

To create a new instance of a window, call the CreateWindowEx function:

建立一个新的窗口实例,可以调用CreateWindowEx函数:

    HWND hwnd = CreateWindowEx(
0,                              // Optional window styles. 窗口样式选项
CLASS_NAME,                     // Window class 窗口类
L"Learn to Program Windows",    // Window text 窗口文本
WS_OVERLAPPEDWINDOW,            // Window style 窗口样式
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL,       // Parent window 父窗口
NULL,       // Menu 菜单
hInstance,  // Instance handle 实例句柄
NULL        // Additional application data 额外的应用程序数据
);
if (hwnd == NULL)
{
return 0;
}

You can read detailed parameter descriptions on MSDN, but here is a quick summary:

你可以详细阅读MSDN上关于这些参数的描述,但是这里有一些快捷的小结:

CreateWindowEx returns a handle to the new window, or zero if the function fails. To show the window—that is, make the window visible —pass the window handle to the ShowWindow function:

CreateWindowEx成功时返回一个窗口句柄,失败时返回0。为了显示出窗口——也就是使窗口变得可见——得通过向ShowWindow函数传送窗口句柄。代码如下:

ShowWindow(hwnd, nCmdShow);

The hwnd parameter is the window handle returned by CreateWindowEx. The nCmdShow parameter can be used to minimize or maximize a window. The operating system passes this value to the program through the wWinMainfunction.

这个hwnd参数就是上一步CreateWindowEx返回的窗口句柄,对于nCmdShow参数,操作系统可以通过这个值在wWinMain执行时使窗口尺寸可变得最小化或最大化。

Here is the complete code to create the window. Remember that WindowProc is still just a forward declaration of a function.

这里有创建窗口的完整代码,记住WindowProc函数总是得在前头先声明:

    // Register the window class.
const wchar_t CLASS_NAME[]  = L"Sample Window Class";
WNDCLASS wc = { };
wc.lpfnWndProc   = WindowProc;
wc.hInstance     = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window.
HWND hwnd = CreateWindowEx(
0,                              // Optional window styles.
CLASS_NAME,                     // Window class
L"Learn to Program Windows",    // Window text
WS_OVERLAPPEDWINDOW,            // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL,       // Parent window
NULL,       // Menu
hInstance,  // Instance handle
NULL        // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);

Congratulations, you've created a window! Right now, the window does not contain any content or interact with the user. In a real GUI application, the window would respond to events from the user and the operating system. The next section describes how window messages provide this sort of interactivity.

恭喜你,你已经创建出了一个窗口!现在,这个窗口没有包含任何内容或者与用户互动的元素。在一个实际的用户图形界面应用程序中,窗口可以响应来自用户的事件或者操作系统的信息,在下一节中描述了“window message(窗口消息)”是如何提供这种交互性的。

学习C++ Windows 编程(你的第一个Windows程序)相关推荐

  1. java类求圆的面积周长_java编程 1. 设计一个求圆的面积和周长的类,要求:1计算当半径r,JAVA编程题。编写一个应用程序计算圆的周长和面积,设圆的半...

    问题标题 java编程 1. 设计一个求圆的面积和周长的类,要求:1计算当半径r,JAVA编程题.编写一个应用程序计算圆的周长和面积,设圆的半 2019-5-23来自ip:15.196.194.53的 ...

  2. 在 windows 环境下,编写一个批处理程序(算命大师.bat)

    在 windows 环境下,编写一个批处理程序(算命大师.bat) 标题 在 windows 环境下,编写一个批处理程序(算命大师.bat) **题目:**在 windows 环境下,编写一个批处理程 ...

  3. 操原上机(一)在 Windows 环境下,编写一个批处理程序(算命大师.bat)

    要求 在 Windows 环境下,编写一个批处理程序(算命大师.bat),程序运行后,输入:出生年月日(例如 2000-07-31).系统输出相应的属相和星座,例如:你属兔, 狮子座.要求:输入进行合 ...

  4. 对《Python核心编程》中“第一个Python程序”的改进

    概述: 本程序主要是模仿<Python核心编程>中3.6节--第一个Python程序,并在其基础上做了一些小的改进,而改进的要求则是来源于第三章的课后练习题. 本篇博客的一个核心问题就是在 ...

  5. crt是什么意思 windows编程_[转]CRT与Windows的关系

    CRT原先是指Microsoft开发的C Runtime Library(C语言运行时库),用于操作系统的开发及运行.后来在此基础上开发了C++ Runtime Library,所以现在CRT是指Mi ...

  6. c语言windows编程句柄,HANDLE句柄(windows编程)

    首先什么是句柄?(理解了句柄,也就知道了句柄和指针的区别了) 所谓句柄实际上是一个数据,是一个Long (整长型)的数据. 句柄是WONDOWS用来标识被应用程序所建立或使用的对象的唯一整数,WIND ...

  7. 第一个java程序释义_Java 学习之路(1)第一个Java程序

    Hello World程序 在编程语言的世界里,第一个编程语言估计就是输出Hello World了吧. /** * 编写第一个Java程序,输出Hello World! * @author LJS * ...

  8. Windows 10或成为最后一个Windows版本

    据The Verge报道,在近日举行的微软Ignite大会上,微软开发大使Jerry Nixon透露了一则消息,"Windows 10将是Windows的最后一个版本",未来将会是 ...

  9. CEVA-X16自由式编程-2-编写第一个“应用程序”

    note:本文是我的原始文章的中文重写版本,语义上可能有一定出入 DSP地址空间"服务器" 在本文中,我尝试利用CEVA-X16自由式编程-1-指令穷举一文中所做的探索,用已知的汇 ...

  10. Windows 2008 Windows7 针对某一个应用程序 取消用户账户控制

    修改注册表: Windows 7 在 HKEY_CURRENT_USERS\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\La ...

最新文章

  1. 使用 Flex 布局与其他普通布局的简单对比
  2. faster rcnn源码解读(三)train_faster_rcnn_alt_opt.py
  3. Google Maps API编程资源大全
  4. Java基础---分支结构(if--else / switch---case)
  5. 网络编程demo之Udp和URL
  6. php 二维数组传递给 js 问题解决记录
  7. 李航《统计学习方法》第四章课后答案链接
  8. @SuppressWarnings注解的详解
  9. OTC场外交易平台源码/虚拟场外交易源码
  10. 大众点评字WOFF字体解密
  11. 用Python对全国火车站数量进行分析,发现东北三省竟然占了2成
  12. C语言网络编程:recv函数详解
  13. ViewGroup详解
  14. VariantNet--简易的神经网络做DNA测序
  15. Agile PLM 表结构说明
  16. 电脑微软商店消失解决办法
  17. 你可能不知道的21个PS技巧
  18. EMD(Exploiting Modification Direction)
  19. 全景图的种类及opencv实现
  20. 最新前端体系学习路径推荐(内附免费资料)

热门文章

  1. 统计某个班男女生人数_sql练习题
  2. ECUG 演讲分享 | 刘奇:Chaos Engineering at PingCAP
  3. python如何删除文件delete file?
  4. mooc软件工程(北大)
  5. java matcher函数_在Java正则表达式中使用Matcher.end()方法
  6. 这60部经典电视剧,看过10部以上说明你真的老了!
  7. java寂静岭 攻略,寂静岭1
  8. 详解vant组件应用于Vue2
  9. 腾讯QQ 2004II BETA3 发布了
  10. android 上传图片进度条,Android带进度条的文件上传示例(使用AsyncTask异步任务)...