孙鑫VC++讲座笔记

合集下载

孙鑫VC学习笔记第8课

孙鑫VC学习笔记第8课
5.状态栏编程
a.Indicator[]数组中有状态栏的信息
如果要增加,可以在String Table中加入一个IDS_Timer,然后将其加入到[]中。
b.在时间栏显示时间,代码略,比较简单
6.进度栏
a.增加成员变量,CProgressCtrl m_progress
b.OnCreate中 m_progress.Create(WS_CHILD | WS_VISIBLE,// | PBS_VERTICAL,
第二种ShowControlBar(&m_newToolBar,!m_newToolBar.IsWindowVisible(),FALSE);
e.将菜单增加复选标记。在OnUpdateUI中加入代码
pCmdUI->SetCheck(m_newToolBar.IsWindowVisible());
然后将其初始化
c.然后在定时器中实现
3.工具栏的编程
a.加入分隔符的方法,向右拖动即可;
b.删除按纽的方法,拖出即可。
4.创建一个新的工具栏的方法
a.插入一个工具栏,画出其图形。
b.在头文件中,定义CToolBar m_newToolBar
c.在MainFrm.cpp的OnCreate()中调用
cs.lpszClass=AfxRegisterWndClass(CS_HREDRAW | CS_VREDRAW);
OnCreate()中
SetClassLong(m_hWnd,GCL_HBRBACKGROUND,(LONG)GetStockObject(BLACK_BRUSH));
m_progress.Create(WS_CHILD | WS_VISIBLE | PBS_SMOOTH,

孙鑫老师的VC视频笔记

孙鑫老师的VC视频笔记

申明本人什么功劳都没有,以上所有都是参考“虎非龙“所写的视频笔记。

望大家不要误会VC视频教程笔记目录第1课Windows程序运行原理及程序编写流程 (3)第2课类的编写与应用 (5)第3课讲述MFC AppWizard的原理与MFC程序框架的剖析 (6)第4课第4课MFC消息映射机制的剖析讲述如何运用ClassWizard (8)第五课文本编程 (11)第6课菜单编程 (15)第7课对话框用户界面程序的编写 (21)第8课逃跑按钮的巧妙实现 (23)第9课如何修改MFC AppWizard向导生成的框架程序的外观和大小 (24)第10课图形的绘制,如何使用自定义画笔 (27)第11课如何让CDC上输出的文字、图形具有保持功能 (29)第12课文件操作 (31)第13课使用CArchive类对文件进行操作 (33)第14课网络编程 (35)第15课多线程与网络编程 (40)第16课事件内核对象、关键代码段(临界区)的讲解 (44)第17课进程间通信 (47)第18课ActiveX编程 (55)第19课DLL编程 (57)第20课钩子与数据库编程 (60)第1课Windows程序运行原理及程序编写流程1.MFC生成的C++源文件中都有StdAfx.h,此文件包含了常用的AFX函数的声明,其中有afxwin.h,此文件包含了CRECT,CPoint,CWnd等许多类及其方法的声明。

2.Project->Setting->Debug可以加入命令行参数。

3.在SDK中要加入"windows.h"和stdio.h。

因为LoadCursor,MessageBox等函数的声明在这个文件中。

4.创建一个完整的窗口的四个步骤SDK,1设计窗口类,2注册窗口类,3创建窗口,4显示窗口5.函数名可以代表函数代码的首地址,即可作为函数指针。

6.要查看VC数据类型,可以在MSDN中输入“BOOL”然后选择“DATA TYPE”。

孙鑫VC++讲座笔记

孙鑫VC++讲座笔记

孙鑫VC++讲座笔记-(1)Windows程序内部运行机制1,windows程序设计是种事件驱动方式的程序设计,主要基于消息的。

当用户需要完成某种功能时,需要调用OS某种支持,然后OS将用户的需要包装成消息,并投入到消息队列中,最后应用程序从消息队列中取走消息并进行响应。

2,消息结构:typedef struct tagMSG { // msgHWND hwnd; //接收消息的窗口句柄。

和哪个窗口相关联。

UINT message; //消息标识。

消息本身是什么。

WPARAM wParam; //消息的附加信息。

具体取决于消息本身。

LPARAM lParam;DWORD time; //消息投递时间。

POINT pt; //消息投递时,光标在屏幕上的位置。

} MSG;3,消息队列:每个应用程序OS都为它建立一个消息队列,消息队列是个先进先出的缓冲区,其中每个元素都是一个消息,OS将生成的每个消息按先后顺序放进消息队列中,应用程序总是取走当前消息队列中的第一条消息,应用程序取走消息后便知道用户的操作和程序的状态,然后对其处理即消息响应,消息响应通过编码实现。

4,使用VC编程除了良好的C基础外还需要掌握两方面:一,消息本身。

不同消息所代表的用户操作和应用程序的状态。

二,对于某个特定的消息来说,要让OS执行某个特定的功能去响应消息。

5,Window程序入口:int WINAPI WinMain(HINSTANCE hInstance, // 当前事例句柄。

HINSTANCE hPrevInstance, // 先前事例句柄。

LPSTR lpCmdLine, // 命令行指针int nCmdShow // (窗口)显示的状态);说明:WinMain函数是Windows程序入口点函数,由OS调用,当OS启动应用程序的时候,winmain函数的参数由OS传递的。

6,创建一个完整的窗口需要经过下面四个操作步骤:一,设计一个窗口类;如:WNDCLASS wndcls;二,注册窗口类;如:RegisterClass(&wndcls);三,创建窗口;如:CreateWindow(),CreateWindowEX();四,显示及更新窗口。

孙鑫VC++讲座笔记-(6)菜单编程_

孙鑫VC++讲座笔记-(6)菜单编程_

1,弹出菜单(Pop-up)是不能用来作命令响应的。

1,弹出菜单(Pop-up)是不能用来作命令响应的。

2,MFC中菜单项消息如果利用ClassWizard来对菜单项消息分别在上述四个类中进行响应,则菜单消息传递顺序:View类--Doc类--CMainFrame类--App类。

菜单消息一旦在其中一个类中响应则不再在其它类中查找响应函数。

具体:当点击一个菜单项的时候,最先接受到菜单项消息的是CMainFrame框架类,CMainFra me框架类将会把菜单项消息交给它的子窗口View类,由View类首先进行处理;如果View 类检测到没对该菜单项消息做响应,则View类把菜单项消息交由文档类Doc类进行处理;如果Doc类检测到Doc类中也没对该菜单项消息做响应,则Doc类又把该菜单项消息交还给View类,由View类再交还给CMainFrame类处理。

如果CMainFrame类查看到CMainFrame 类中也没对该消息做响应,则最终交给App类进行处理。

3,消息的分类:标准消息,命令消息,通告消息。

[标准消息]:除WM_COMMAND之外,所有以WM_开头的消息。

[命令消息]:来自菜单、加速键或工具栏按钮的消息。

这类消息都以WM_COMMAND呈现。

在MFC中,通过菜单项的标识(ID)来区分不同的命令消息;在SDK中,通过消息的w Param参数识别。

[通告消息]:由控件产生的消息,例如,按钮的单击,列表框的选择等均产生此类消息,为的是向其父窗口(通常是对话框)通知事件的发生。

这类消息也是以WM_COMMAND形式呈现。

说明:1)从CWnd派生的类,都可以接收到[标准消息]。

2)从CCmdTarget派生的类,都可以接收到[命令消息]和[通告消息]。

4,一个菜单拦可以有若干个子菜单,一个子菜单又可以有若干个菜单项等。

对菜单栏的子菜单由左至右建立从0开始的索引。

对特定子菜单的菜单项由上至下建立了从0开始的索引。

孙鑫VC教学视频学习笔记1-8

孙鑫VC教学视频学习笔记1-8

2:路径层(Path)的概念!
3: 我试图写一个 MyNotePad 的小应用程序,已完成的任务有:设置自定义的图标,窗口背景,光标.在窗口 显示插入符,并让插入符随鼠标的点击而显示在相应的位置,用 TextOut 完成串的输入,显示,并保存于一个 CString 对象中,可是我发现显示文本的背景色(默认是白色)与自定义的窗口背景色不一致,我先是用如下 的代码: hdc.SetBkColor(hdc.GetBkColor)); 来设置文本背景色,可是背景色仍然是默认的白色,我不停地想是不是 SetBkcolor()不可以用,但当时真是 笨,明明用 GetBkColor()取到的就是文本的背景色,你再设置回去,那不就相当于什么都没做嘛!当时脑子 中充斥的想法是以为 GetBkColor()取到的是窗口的背景色呢!呵呵,笨!另外,hdc.SetTextColor ()可以设 置文本的颜色.但还有一个问题:下面是我处理退格键的代码: void CMyNotePadView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default if(0x0d==nChar) { // m_ptOrigin } else if(0x08==nChar) { CClientDC hdc(this); hdc.SetBkColor(RGB(208,221,238)); hdc.SetTextColor(RGB(208,221,238)); hdc.TextOut(m_ptOrigin.x,m_ptOrigin.y,m_strLine); m_strLine=m_strLine.Left(m_strLine.GetLength()-1); } else { m_strLine+=nChar; } ::InvalidateRect(m_hWnd,NULL,FALSE); CView::OnChar(nChar, nRepCnt, nFlags); } 为了应付窗口切换时的重绘,我把输出工作放在了 OnDraw()函数中了,别的都是正常的,可当退格的时候

孙鑫VC++讲座笔记-(5)文本编程

孙鑫VC++讲座笔记-(5)文本编程

1,创建插入符:void CreateSolidCaret( int nWidth, int nHeight );//创建插入符void CreateCaret( CBitmap* pBitmap );//创建位图插入符void ShowCaret( );//显示插入符void HideCaret( );//隐藏插入符static void PASCAL SetCaretPos( POINT point );//移动插入符号说明:1)创建插入符要在窗口创建完成之后,CreateSolidCaret函数创建的插入符被初始化为隐藏,所以需要调用ShowCaret()将其显示。

2)使用CreateCaret函数创建位图插入符的时候,不能使用局部的位图对象关联位图资源。

(与资源相关联的C++对象,当它析构的时候会同时把与它相关联的资源销毁。

)2,获取当前字体信息的度量:CDC::GetTextMetricsBOOL GetTextMetrics( LPTEXTMETRIC lpMetrics ) const;说明:typedef struct tagTEXTMETRIC { /* tm */int tmHeight;//字体高度。

Specifies the height (ascent + descent) of characters.int tmAscent;//基线以上的字体高度int tmDescent;//基线以下的字体高度int tmInternalLeading;int tmExternalLeading;int tmAveCharWidth;//字符平均宽度int tmMaxCharWidth;int tmWeight;BYTE tmItalic;BYTE tmUnderlined;BYTE tmStruckOut;BYTE tmFirstChar;BYTE tmLastChar;BYTE tmDefaultChar;BYTE tmBreakChar;BYTE tmPitchAndFamily;BYTE tmCharSet;int tmOverhang;int tmDigitizedAspectX;int tmDigitizedAspectY;} TEXTMETRIC;3,OnDraw函数:virtual void OnDraw( CDC* pDC )当窗口(从无到有或尺寸大小改变等)要求重绘的时候,会发送WM_PAIN消息,调用OnDraw函数进行重绘。

学习笔记(SunXinvclearningnotes)

学习笔记(SunXinvclearningnotes)

孙鑫vc++学习笔记(Sun Xin vc++ learning notes)1. about creating window applicationsUnderstand the capabilities of the windows program, the API function, the relationship between the message queue and the operating system, the input and output devicesWindow programming, sub background and front deskFront desk for what kind of window, how to display the title,and the destruction of the window, the day after tomorrowcontinue to runBackground is the design purpose, he is through the windowmessage queue continuous access to messages (GetMessage and translation), that is, the winprocess function of the subfunction to call (callback function) to achieve, written by the user himselfMessages are implemented through applications that providefunctions to the system platform to tune the effects of hardware, sound, or images. Applications are built on application systemsThe concrete steps are as followsThe construction of new Win32 Application source programwritten in empty project file with C program source file thatcontains the windows.h file to the WinMain function to writeit contains the main function of this program with the function of DOS under the same entrance when the application ends its WinMain function at the end is called by the operating systemallocates space assignmentThe program design includes: the definition of WinMain function to create a window to create a message loop write windowprocedure four step window: design a window class (fill in the blank window display status includes cursor display background loading icon loadicon window function lpfnWndProc messageresponse function by its own o perating system, but need to write code to call) registered window class Registerclass to createa window (createWindow window size coordinate menu handle and update updateWindow ShowWindow) display window of eachfunction type operating system is basically fixed again to set a message l oop while (GetMessage (corresponding to the message size and member variables) the corresponding applicationmessage queue) to achieve continuous operation program (background) TranslateMessage (converted to wchar) Thedistribution (dispatchmessage to the middle layer of thecallback function for operating system) the last messageediting window function switch (process to deal with the mouse button to destroy the window and the end of the news programplus default) prompt: the system is through the window function address (pointer) to invoke the process window function2, about c++C++ has more advantages over C, mainly in encapsulation,inheritance and polymorphismSelect new project Win32 console application c++ source filewritten in structure c++ body can write function of foreign body and the structure can call the member v ariable c++ function insimilar but by default to the member v ariable access is not the sameAn instance of a class and object instantiated with an objectthat defines a structure variable is to produce an objectConstructor: the important function is to create the objectitself, and each object must have a constructor that has thesame form as the class name and has no return value,In a statement object will automatically call the defaultconstructor is a constructor with no parameters are onlyresponsible for creating object not initialized if thedefinition of a parameter or a zeroary constructor, c++ willnot create a default constructorDestructor: the object is responsible for retrieving its memory space at the end of the object's life. In contrast to theconstructor, the arguments and return values are not allowed,and a class can only have one destructor.Overloading of functions: if the constructor overloads, c++ automatically matches the call to the corresponding function, overloading the condition: the parameter type of the functionand the number of argumentsThis pointer: an implicit pointer to an object correspondingto itself, representing the address of the object (this=&pt).This makes it easy to write the member v ariables in the object (using VC's automatic listing of member functions, usingthis >)Base class inheritance and access characteristics of the three kinds of subclasses to inherit father to see the definition of property inheritance characteristics and the parent classmember function decision, protected in subclassing but outside (such as fish.breath (main) in the function cannot be calledby the fish class but can not be inherited) visit the subclass inheritance, if the parent class with parameters, the subclass inheritance should also add parameters, the constructor callthe parent class and subclass, and the destructor calls inreverse orderOverlay of functions: a member variable that occurs between the two classes of a parent class and a subclass. The name of thefunction is consistent. Scope identifier (::) used to indicate which class of member variables the function belongs to andprevents the coverage of the member functions of the parentclassPolymorphism: virtual in the base class member function, subclass inheritance, VC sub class visit, sub class has a memberfunction with the same name is called sub classes, subclassesdid not call the parent class. Another: pure virtual functions appear in base classes, but are implemented by derived classesReference and pointer: int a=5; int &b=a; a, B, point to thesame m emory s pace at the same t ime, AB i s an alias pointer, and the variable itself occupies memory, which stores the contentas the address pointing to the variableFor write method of.Cpp file and.H file, create different filesin the open the project can also be found in the project filenew text file (later renamed F2, VC function keys) to add oneto write different engineering documentsVC program to compile and link mechanism: precompiled < > "",and when the project file is established to find the solutionto the project file, header file contains repeated problems:#ifdef XX #define XX (preparation) after adding ENDIF, repeatthis definition can prevent the error, prevent the VCcompilation process mechanism integration: the pre processorto the pre compiled instruction compiler (#) to project source code (.Cpp) separately compiled machine instructions contains different object file (debag.Obj file), and finally by theconnector to the target file (.Obj) and c++ standard libraryfunction standard library (.Lib) to generate a the executablefile (.Exe). Tip: compile time to troubleshoot.Cpp source files individually!3 MFC programmingAn object oriented library of functions is provided to usersin a class mannerMFC AppWizard is used to create a single document based on the MFC interface (SDI) applications, the new MFC AppWizardgeneration program dialog box click OK can see the operationof the program, on the left side of VC w orkspace classview tag can be seen in the five class of the automatically generated,only need to turn on the following class you can write codeFirst of all, to understand the internal mechanism of MFC, y oucan find that the WinMain function is not found in findfile,but search the WinMain function (not the file) in the MFC file SRC file (the source code of MFC) i n the installation directory Under the care, five classes (where CMainFrame i s a fixed name, which is derived from CFrameWnd and CWnd derived from the window class) is how t o combine with WinMain. (hint: for all the global variables in global), the global object global variables areassigned to memory before WinMain you can search the cwinapp, initialization function view defines its constructor good(window tab to switch VC),An example application is told by the instance handle(parameter hinstance WinMain function) to mark, and for MFC applications through the object application class to uniquely identify the application examples of each MFC program and only a copy of the application class (CwinApp) derived class, every MFC there is only one instance of the derived classinstantiation of objects, theApp is the global object, theobject that the application itself, before the theApp CTestApp object constructor call will call the superclass constructor, and from associating our own program to create the class and Microsoft provides the base class. The CWinApp constructor completes some i nitialization when the program is running. The lookup cwinapp will find that it is a constructor with aparameter, and we do not pass arguments to the base class when we inherit, because cwinapp is the constructor with the default value.When the program calls the constructor of the cwinapp class,and the implementation of the ctestapp class constructor, and produced a theapp object, then enter the WinMain function, theWinMain function is actually can be found by calling theafxwinmain function to complete the function (AFX for theapplication frame function)In accordance with the procedures for the preparation of Win32 steps to design the window class and register window classshould create the window window created in MFC function isrealized by createx CWnd functions of the function declarationin the afxwin.h fileCframe is the operation of the window function is marked CView window when the program is running the following blank window precreatwindow (using virtual function polymorphism allows programmers to modify the appearance of the window in the subclass) it extended function in creatwindow before theexecution of MFC suffix function called ex isMFC window class internal operation summary:1, first, you start the application with the global application object theapp, which is the global object, and the this pointer in the base class cwinapp can point to the object. Without this global object, the program does not make e rrors at compile time,But there will be errors at runtime2 call the global application object constructor, which willbe the base class constructor cwinapp electrophoresis, thelatter performs some initialization application, and theapplication of object pointers stored3 enter the WinMain function, in the afxwinmain function. Inthe afxwinmain function can obtain the subclass (for testapplications, is the ctestapp class pointer, the pointer) bycalling a virtual function: InitInstance function, whichperforms some i nitialization application, including the window class is registered, create, display and update. The createxfunction is called multiple times because a single document MFC application has multiple windows, including the frame window, toolbar, status bar, and so on4 entering the message loop, although the default processfunction is set, the MFC application uses a messaging mechanism to process various messages, and when you receive the wm_QUIT message, exit the message loop and end the programThe cdocument class is a document class that is not derived from the CWnd class, so it is not a window class. MFC provides adocument / view architecture, including document refers to the cdocument class, as is CView, data storage and loading is accomplished by a document type, display and modify the datato be completed by the visual category, thus the data management and display method of separationThe caboutdlg class is derived from the CDialog class, whichis born in CWnd, so it is the window class, which primarilyprovides program related help information, such as versionnumbersTip: in the definitions of the member f unctions themselves, if the call API (provided by window) function and their functionis different, so the API function name c an not be added: symbols,the compiler automatically identifies the API function, but if the API function member function and internal call currentlydefined is the same a s that of the latter the front must be added: symbols, otherwise the program will fail at runtime or compileUse the source code to write a button control, pay attentionto add to the corresponding class become the private member variables, and the corresponding function create createdisplay control code written in vc++, as a kind of add a message processing function method is: in the classview tab, rightclick on the the class name, select the {add window message handler..} menu command from the shortcut menu pop-up, thenpop-up selection dialog box, select the key position to add the wm_create control message. See this pointer to the class,rather than the source positionThis chapter finds that many window class function calls nolonger need to pass window handles because they all maintaina window handle member variable internally4. simple drawingAnalyze the MFC message mapping mechanism, design a drawing program to understand messaging and captureAfter analysis, a MFC message response function has threerelevant information in the program: the function prototype,the function implementation, and the macro used to correlatethe message and the message response function. The statementin the header file that is the prototype of the message r esponse function between the two AFX_MSG_ annotation macros. There aretwo sources in the file: one is the message mapping macrobetween the two AFX_MSG_MAP annotations,Through this macro, the message i s associated with the message response function; the other is the implementation code of the message response function in the source file.In the first chapter of the news cycle, when the message is generated, the operating system will put the message into the application queue, took out a specific message throughGetMessage function and dispatchmessage function through the message to the operating system, the window procedure call application wndproc processing, switch - case structure. Themessage and the discriminant function, and in the MFC is notin accordance with this method, as long as the definition ofthree messages a ssociated with the message, you can achieve the response message. That is, the MFC message mapping mechanism.In fact, message r outing can have a variety of ways, one of which is the definition of a virtual function for each message i n the base class, the polymorphism... But this approach is notdesirable, because the virtual function must be a virtualfunction table to achieveMFC message mapping mechanism specific method: in each classthat can receive and process messages, define a message and message static comparison table, that is, the message mappingtable. In the message map table, the message and thecorresponding message processing function pointer appear inpairs. A class can process all the messages and theircorresponding message p rocessing letters, and the addresses of学习好资料欢迎下载the numbers are listed in the static list corresponding to this class. When a message needs to be processed, the program searches the static table of the message to see if the message exists in the table, so that it can tell whether the class canprocess the message. If you can process the message, it is also easy to find and call the corresponding message handlerfunction in the same way as the static table。

孙鑫笔记2

孙鑫笔记2

4, PreCreateWindow()是个虚函数,如果子类有则调用子类的。
5, CreateWindowEx()函数参数与CREATESTRUCT结构体成员完全一致,CreateWindowEx()函数与CREATESTRUCT结构体参数的对应关系,使我们在创建窗口之前通过可PreCreateWindow(cs)修改cs结构体成员来修改所要的窗口外观。
对于MFC程序,MainFrame,View,ToolBar,Controlbar等都是窗口,所以下面的窗口注册与创建、显示等要反复调用多次,一次对应一个窗口
(1) 注册窗口类
AfxEndDeferRegisterClass
(2) 创建窗口
CMainFrame::PreCreateWindow()//反复调用一次是给我们修改窗口属性的机会
一、C语言程序执行步骤
在C语言中,大约的步骤如下:
1, 全局变量内存分配 要是初始化)
打开一个MFC APPWizard(exe)工程,跟踪其执行步骤,可以发现,是以下顺序:
1) CXXApp中的全局变量定义
1) 设计一个窗口类
2) 注册窗口类
3) 创建窗口
4) 显示及更新窗口
5) 消息循环
补充2:其他需要注意的几点
1, 每一个MFC程序,有且只有一个从WinApp类派生的类(应用程序类),也只有一个从应用程序类所事例化的对象,表示应用程序本身。在WIN32程序当中,表示应用程序是通过WINMAIN入口函数来表示的(通过一个应用程序的一个事例号这一个标识来表示的)。在基于MFC应用程序中,是通过产生一个应用程序对象,用它来唯一的表示了应用程序。
6,注意两个函数。
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

孙鑫VC++讲座笔记(1)Windows程序内部运行机制1,windows程序设计是种事件驱动方式的程序设计,主要基于消息的。

当用户需要完成某种功能时,需要调用OS某种支持,然后OS将用户的需要包装成消息,并投入到消息队列中,最后应用程序从消息队列中取走消息并进行响应。

2,消息结构:typedef struct tagMSG { // msgHWND hwnd; //接收消息的窗口句柄。

和哪个窗口相关联。

UINT message; //消息标识。

消息本身是什么。

WPARAM wParam; //消息的附加信息。

具体取决于消息本身。

LPARAM lParam;DWORD time; //消息投递时间。

POINT pt; //消息投递时,光标在屏幕上的位置。

} MSG;3,消息队列:每个应用程序OS都为它建立一个消息队列,消息队列是个先进先出的缓冲区,其中每个元素都是一个消息,OS将生成的每个消息按先后顺序放进消息队列中,应用程序总是取走当前消息队列中的第一条消息,应用程序取走消息后便知道用户的操作和程序的状态,然后对其处理即消息响应,消息响应通过编码实现。

4,使用VC编程除了良好的C基础外还需要掌握两方面:一,消息本身。

不同消息所代表的用户操作和应用程序的状态。

二,对于某个特定的消息来说,要让OS执行某个特定的功能去响应消息。

5,Window程序入口:int WINAPI WinMain(HINSTANCE hInstance, // 当前事例句柄。

HINSTANCE hPrevInstance, // 先前事例句柄。

LPSTR lpCmdLine, // 命令行指针int nCmdShow // (窗口)显示的状态);说明:WinMain函数是Windows程序入口点函数,由OS调用,当OS启动应用程序的时候,winmain函数的参数由OS传递的。

6,创建一个完整的窗口需要经过下面四个操作步骤:一,设计一个窗口类;如:WNDCLASS wndcls;二,注册窗口类;如:RegisterClass(&wndcls);三,创建窗口;如:CreateWindow(),CreateWindowEX();四,显示及更新窗口。

如:ShowWindow(),UpdateWindow();说明:创建窗口的时候一定要基于已经注册的窗口类.7,Windows提供的窗口类:typedef struct _WNDCLASS {UINT style; //窗口的类型WNDPROC lpfnWndProc; //窗口过程函数指针(回调函数)int cbClsExtra; //窗口类附加字节,为该类窗口所共享。

通常0。

int cbWndExtra; //窗口附加字节。

通常设为0。

HANDLE hInstance; //当前应用程序事例句柄。

HICON hIcon; //图标句柄 LoadIcon();HCURSOR hCursor; //光标句柄 LoadCursor();HBRUSH hbrBackground; //画刷句柄 (HBRUSH)GetStockObject();LPCTSTR lpszMenuName; //菜单名字LPCTSTR lpszClassName; //类的名字} WNDCLASS;8,窗口类注册:ATOM RegisterClass(CONST WNDCLASS *lpWndClass // address of structure with class // data);9,创建窗口:HWND CreateWindow(LPCTSTR lpClassName, // pointer to registered class nameLPCTSTR lpWindowName, // pointer to window nameDWORD dwStyle, // window styleint x, // horizontal position of windowint y, // vertical position of windowint nWidth, // window widthint nHeight, // window heightHWND hWndParent, // handle to parent or owner windowHMENU hMenu, // handle to menu or child-window identifier HANDLE hInstance, // handle to application instanceLPVOID lpParam // pointer to window-creation data);10,显示和更新窗口窗口:BOOL ShowWindow(HWND hWnd, // handle to windowint nCmdShow // show state of window);BOOL UpdateWindow(HWND hWnd // handle of window);11,消息循环:MSG msg;while(GetMessage(&msg,...)) //从消息队列中取出一条消息{TranslateMessage(&msg); //进行消息(如键盘消息)转换DispatchMessage(&msg); //分派消息到窗口的回调函数处理,(OS调用窗口回调函数进行处理)。

}其中://**The GetMessage function retrieves a message from the calling thread's message queue and places it in the specified structure.//**If the function retrieves a message other than WM_QUIT, the return value is nonzero.If the function retrieves the WM_QUIT message, the return value is zero. If there is an error, the return value is -1.BOOL GetMessage(LPMSG lpMsg, // address of structure with messageHWND hWnd, // handle of windowUINT wMsgFilterMin, // first messageUINT wMsgFilterMax // last message);//The TranslateMessage function translates virtual-key messages into character messages. The character messages are posted to the calling thread's message queue, to be read the next time the thread calls the GetMessage or PeekMessage function. BOOL TranslateMessage(CONST MSG *lpMsg // address of structure with message);//The DispatchMessage function dispatches a message to a window procedure. LONG DispatchMessage(CONST MSG *lpmsg // pointer to structure with message);12,窗口过程函数(回调函数)原型:The WindowProc function is an application-defined function that processes messages sent to a window. The WNDPROC type defines a pointer to this callback function. WindowProc is a placeholder(占位符) for the application-defined function name.LRESULT CALLBACK WindowProc( //这里WindowProc是个代号名字。

HWND hwnd, // handle to windowUINT uMsg, // message identifierWPARAM wParam, // first message parameterLPARAM lParam // second message parameter);说明:两种函数调用约定(__stdcall 和 __cdecl):#define CALLBACK __stdcall//__stdcall 标准调用预定,是PASCAL 调用约定,象DELPHI使用的就是标准调用约定#define WINAPIV __cdecl// __cdecl 是C 语言形式的调用约定。

主要区别:函数参数传递顺序和对堆栈的清除上。

问题:除了那些可变参数的函数调用外,其余的一般都是__stdcall约定。

但 C/C++编译默然的是__cdecl约定。

所以如果在VC等环境中调用__stdcall约定的函数,必须要在函数声明的时加上 __stdcall 修饰符,以便对这个函数的调用是使用__stdcall约定(如使用DELPHI编写的DLL时候)。

(VC中可通过这途径修改:project|settings..|c/c++|...)在窗口过程函数中通过一组switch语句来对消息进行处理:如:LRESULT CALLBACK WindowProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam){switch(uMsg){case WM_PAINT:...break;case ...break;case WM_CLOSE://DestroyWindow(hwnd);//销毁窗口,并发送WM_DESTROY消息。

break;case WM_DESTROY://PostQuitMessage(0);//发送WM_QUIT消息到消息队列中,请求终止。

//GetMessage()取到WM_QUIT消息后,返回0,退出消息循 // 环,从而终止应用程序。

相关文档
最新文档