C ++ MFC common functions), mfc Functions

Source: Internet
Author: User

C ++ MFC common functions (conversion) and mfc Functions

WinExec ()

ExitWindowsEx ()

GlobalMemoryStatus ()

GetSystemInfo ()

GetSystemDirectory ()

GetWindowsDirectory ()

GetTaskmanWindow () // obtain the taskbar window handle in user32.dll

OpenProcessToken () opens an access token for a process.

GetCurrentProcess () Get the Process Handle

LookupPrivilegeValue () Modify process Permissions

AdjustTokenProvileges () notifies WindowsNT to modify this process right

CreateRectRgn ()

CreateEllipticRgnIndirect ()

PtInRegion ()

CommandToIndex () ID to index value

Menu type:

DrawMenuBar () re-draw menu

SetDefaultItem () sets the default menu item

CheckMenuItem () sets the Check status of the menu item

CreatePopupMenu () Creation menu

Window class:

MoveWindow ()

Invalidate () indicates that the window is invalid. If the window is invalid, the window is repainted.

GetParent () obtains the parent window handle of the window.

BringWindowToTop () Place the window to the top

SetWindowPos ()

DeferWindowPos ()

SetActiveWindow () activates the top-level window

Set/GetForegroundWindow () Set/get foreground window, return handle

Set/GetWindowLong () change window attributes

GetNextWindow () Get the next window handle

GetWindow () get window handle

FromHandle () Get pointer through handle

AfxGetInstanceHandle () gets the current instance handle of the program

AfxRegisterWndClass ()

Set/GetClassLong ()

Set/GetWindowLong ()

GetWindowRect () obtains the Rect of the window on the screen.

Dialog Box:

GetDlgItem ()

Set/GetDlgItemText ()

Set/GetDlgItemInt ()

Set/GetDlgItem ()

SendDlgItemMessage ()

SetFocus () text Edit box Edit Control to respond to press enter message, must be set to multi-row type

GetNextDlgTabItem () obtains the next control handle with the TABStop attribute.

OnCtlColor () WM_CTLCOLOR window draws the message Response Function

GetDlgCtrlID ()

SetButtonText () Setting button text CreateRectRgn

GetStartPosition ()

GetNextPathName ()

SetHorizontalExtent ()

SHBrowseForFolder ()

Attribute form:

SetWizardMode ()

SetWizardButtons ()

OnSetActive ()

Toolbar:

RecalcLayout ()

ShowControlBar ()

Status Bar:

CommandToIndex () obtains the index value based on the ID.

SetMessageText ()

GetMessageBar ()

GetDescendantWindow ()

Graphics

OnEraseBkgnd ()

CButton: DrawItem ()

SetBkMode (): Set the text background

SetTextColor ()

SetBkColor ()

SetROP2 ()

SetClipRtn ()

DrawText ()

BeginPath ()

EndPath ()

BeginPaint ()

EndPaint ()

GetTextExtend ()

SetWorldTransform ()

GetDeviceCaps ()

Set/GetViewportOrg ()

Set/getdomainworg ()

DPtoLP () converts device coordinate points into logical coordinate points

LPtoDP () converts logical coordinate points into device coordinate points

DeleteMetaFile ()

CopyMetaFile ()

GetMetaFile ()

GetEnhMetaFile ()

Void CView: OnPaint ()

{

CPaintDC dc (this );

OnPrepareDC (& dc );

OnDraw (& dc );

}

File Operations:

EncryptFile ()

CreateFile ()

ReadFile ()

WriteFile ()

SetFilePointer ()

: WriteProfileString (): Write related information to win. ini.

: GetProfileString () Get related information from win. ini

CWinApp: WriteProfileString () Write related information to the Registry

CWinApp: GetProfileString () get relevant information from the Registry

: WritePrivateProfileString ()

RegCreateKeyEx () create a registry key

RegCloseKey () closes the registry key

RegOpenKeyEx () Open the registry key

RegSetValueEx () writes to the registry key

RegQueryValueEx () reads the registry key

RegEnumKeyEx ()

RegDeleteKey ()

Document view:

HOOK:

SetWindowsHookEx ()

CallNextHookEx ()

UnhookWindowsHookEx ()

GetCurrentThreadID ()

GetModuleHandle ()

Dynamic Library:

# Pragma data_seg ()

# Pragma comment (linker, "/section: XXX, RWS") R readable W writable S shared

SEGMENTS

XXX READ WRITE SHARED

MAKEINTRESOURCE ()

GetProcAddress () Get the function address

LoadLibrary () Load Dll

FreeLibrary () reduces the Dll reference count

Multithreading:

CreateThread ()

CloseHandle ()

Mutex:

CreateMutex ()

ReleaseMutex ()

WaitForSingleObject ()

Event:

CreateEvent ()

SetEvent () is set to Signal Status

ResetEvent () is used to set the signal-free status.

Critical section:

EnterCriticalSection ()

InitializeCriticalSection ()

LeaveCriticalSection ()

DeleteCriticalSection ()

Asynchronous socket:

WSAAsyncSelect () Requests network message notifications for a socket

WSAEnumProtocols () retrieval of available network communication protocols

WSASocket ()

Clipboard:

OpenClipboard () Open the clipboard

CloseClipboard () Close the clipboard

EmptyClipboard () clears the clipboard

SetClipboardData ()

GetClipboardData ()

GlobalAlloc ()

GlobalLock ()

GlobalUnlock ()

IsClipboardFormatAvailable ()

Anonymous pipeline:

CreatePipe ()

CreateProcess ()

CreateFile ()

ReadFile ()

WriteFile ()

Named Pipe:

CreateNamedPipe ()

ConnectNamedPipe ()

WaitNamedPipe ()

CreateFile ()

ReadFile ()

WriteFile ()

Mail trough:

CreateMailslot ()

Multimedia:

MciSendCommand () <mmsystem. h>

Mutual conversion of window, control pointer and handle

1 pointer to handle

In the MFC application, you must first obtain the window pointer and then convert it into a handle.

CWnd * pWnd;

HANDLE hWnd = pWnd-> GetSafeHwnd ();

2. Convert the handle to a pointer.

In the MFC application, obtain the handle of the dialog box Control and Its pointer.

HANDLE hWnd;

GetDlgItem (IDC_xxx, & hWnd );

CWnd * pWnd = FromHandle (hWnd );

How to obtain the program window pointer

1. Obtain the window pointer of the main framework (it can be used at any time, as long as it is in the MFC Program)

CWnd * pWnd = AfxGetMainWnd ();

2. Obtain the control pointer in the dialog box.

CWnd * pWnd = GetDlgItem (IDC_xxx );

3. Obtain the handle of a control in the dialog box.

HANDLE GetDlgItem (m_hDLG, m_nID_DlgItem );

4. Obtain the handle of the GDI object

HANDLE m_hGDIObj = m_pGDIObj-> GetSafeHanle ();

1. How can I obtain the instance handle of an application? AfxGetInstanceHandle ()

The application instance handle is stored in CWinAppIm_hInstance. You can call AfxGetInstancdHandle to obtain the handle.

Example: HANDLE hInstance = AfxGetInstanceHandle ();

2. How to get the pointer to the main window of the application through code? AfxGetMainWnd GetSafeHwnd () AfxGetAppName () AfxGetThread

The pointer of the main window is saved in CWinThread: m_pMainWnd, And the AfxGetMainWnd implementation is called.

[Example] AfxGetMainWnd ()-> ShowWindow (SW_SHOWMAXMIZED); // maximize the program.

[Example] In this example, the main window is a dialog box. The following code is to implement related functions in another CFileTreeCtrl class (sub-window) in the Main Dialog Box (Main Window) in the following static text box (sub-window:

CWnd * m_pCWnd = AfxGetMainWnd (); // obtain the main window pointer and access other sub-window resources through the main window pointer.

// Method 1

M_pCWnd-> SetDlgItemText (IDC_STATIC_path, "CWnd *" + m_sCurPath); // display the string in the subwindow (ID: IDC_STATIC_path) in the main window

M_pCWnd-> SetDlgItemText (IDC_STATIC_who, "Path Display completed by FileTreeCtrl class :");

// Method 2

M_pCWnd-> SendMessage (STN_CLICKED); // send a message to the main window. The display task is completed in the main window.

// The. cpp in the main window contains the ON_MESSAGE (STN_CLICKED, OnSTATICpath3) description.

// Some functions must be accessed through the window handle. We can use method 3 below

// CWnd: GetSafeHwnd

// Returns the window handle for a window

// HWND GetSafeHwnd () const;

HWND m_hWnd_tree = GetSafeHwnd (); // [note] only the handle of the current window (FileTree class) is obtained here.

HWND m_hWnd = m_pCWnd-> GetSafeHwnd (); // the handle of the main window (the handle of the main window is obtained by the main window pointer)

// BOOL SetWindowText (HWND hWnd, LPCTSTR lpString)

: SetWindowText (m_hWnd, "ok2222"); // modify the title of the main window.

: SetDlgItemText (m_hWnd, IDC_STATIC_path2, "HWND:" + m_sCurPath );

[Also] AfxGetThread

CWinThread * AfxGetThread ();

Return Value: Pointer to the currently executing thread.

3. How to Get icons of other programs in the program? AfxGetInstanceHandle ()

HINSTANCE AfxGetInstanceHandle ();

Return Value

An HINSTANCE to the current instance of the application. If called from within a DLL linked with the USRDLL version of MFC, an HINSTANCE to the DLL is returned.

Remarks

This function allows you to retrieve the instance handle of the current application. afxGetInstanceHandle always returns the HINSTANCE of your executable file (. EXE) unless it is called from within a DLL linked with the USRDLL version of MFC. in this case, it returns an HINSTANCE to the DLL.

Two methods:

(1) the SDK function SHGetFileInfo or use ExtractIcon to obtain the handle (handle) of the icon resource ),

(2) the SDK function SHGetFileInfo obtains a lot of information about the file, such as the size icon, attribute, and type.

Example (1): the NotePad icon is displayed in the upper left corner of the program window.

Void CSampleView: OnDraw (CDC * pDC)

{

If (: SHGetFileInfo (_ T ("c: \ pwin95 \ notepad.exe"), 0,

& StFileInfo, sizeof (stFileInfo), SHGFI_ICON ))

{

PDC-> DrawIcon (10, 10, stFileInfo. hIcon );

}

}

Example (2): Same Function, Use ExtractIcon Function

Void CSampleView: OnDraw (CDC * pDC)

{

HICON hIcon =: ExtractIcon (AfxGetInstanceHandle (), _ T

("NotePad.exe"), 0 );

If (hIcon & hIcon! = (HICON)-1)

PDC-> DrawIcon (10, 10, hIcon );

}

[Note] the paths for obtaining system files, such as win. ini system32.ini, are different in different systems. For example:

In general, the GetWindowsDirectory function is used to obtain the notepad.exe path;

If you are calling the paint brush under win95, You Should access the registry to obtain its path;

To make a more sophisticated program, we should consider it comprehensively.

[Other]

HINSTANCE AfxGetResourceHandle ();

Return Value: An HINSTANCE handle where the default resources of the application are loaded.

4. GetDesktopWindow ()

Example in MSDN:

// The static function CWnd: getdomaintopwindow returns the pointer of the desktop window. The following example illustrates the MFC

Void CFrameWnd: BeginModalState ()

{

// First count all windows that need to be disabled

UINT nCount = 0;

HWND hWnd =: GetWindow (: get1_topwindow (), GW_CHILD );

While (hWnd! = NULL)

{

If (: isw.wenabled (hwnd )&&

CWnd: FromHandlePermanent (hWnd )! = NULL &&

AfxIsDescendant (pParent-> m_hWnd, hWnd )&&

: SendMessage (hWnd, WM_DISABLEMODAL, 0, 0) = 0)

{

++ NCount;

}

HWnd =: GetWindow (hWnd, GW_HWNDNEXT );

}

}

// User problem: the following program does not take the same program handle, but the result returned by GetModuleFileName is the same.

HWND ChWnd; // subwindow handle

HWND hwDesktop =: GetDesktopWindow (); // obtain the desktop handle

ChWnd =: GetWindow (hwDesktop, GW_CHILD); // obtain the desktop sub-Handle

CString csTitle, csClass, csTm, mLookstring;

Char szBuffer [255];

While (ChWnd! = NULL) // cyclically fetch the same level handle of the sub-Handle

{

If (: IsWindowVisible (ChWnd) // determines whether the window is displayed.

{

: GetWindowText (ChWnd, csTitle. GetBuffer (255), 254 );

: GetClassName (ChWnd, csClass. GetBuffer (255), 254 );

CsTitle. ReleaseBuffer (); // Title

CsClass. ReleaseBuffer (); // Class Name

CsTm. Format ("% 08X:", ChWnd );

If (csTitle = "")

{

MLookstring = csTm + csClass;

} Else

{

MLookstring = csTm + csTitle;

}

// The Window handle here is not the same program? (Problem !) But the result is the same for shifmo.

HINSTANCE hInstance = (HINSTANCE): GetWindowLong (ChWnd, DWL_USER );

: GetModuleFileName (hInstance, szBuffer, sizeof (szBuffer ));

MessageBox (szBuffer, mLookstring );

}

ChWnd =: GetWindow (ChWnd, GW_HWNDNEXT );

}

Answer:

The problem is that GetWindowLong (ChWnd, DWL_USER) in Win32 always returns the hInstance currently running, so the file name you get is always one. Therefore, you must enumerate all "process program names" to obtain the program names.

=== What is the difference between the handle and pointer?

Many of my friends who are learning VC have heard of pointer and handle.

However, the differences between them are often unclear.

First, the handle is a sign of a window, that is, all the elements inherited from the CWND class, which have the handle member.

What he can do is the only window that represents a desktop. A pointer is an address. If it points to an object in memory, you can perform any operation on it. Of course, it is not limited to your own applications, if you can get a pointer to an object of another application, you can also perform operations. However, to obtain the pointer, you must first find the handle of the window and use the FromHandle function to obtain the pointer.

=== Question 1:

How to send a string in a custom message? For example:

SendMessage (MyWnd, WM_USERDEFINED, 0, 0)

How do I write string Buffer into wParam or lParam?

You can pass the string address, because the address is exactly 32 characters. For example:

Char s [256];

SendMessage (MyWnd, WM_USERDEFINED, (WPARAM) s, 0)

The receiver only needs to assign wParam to a char. However, this method can only be used to transmit data within a process.

=== Question 2:

1. in the VC application framework, how do I add a self-made class and define the Class Object? Can I generate this object only when I click a menu item with the mouse? (The constructor of this class has parameters ).

2. Message sending function:

PostMessage (HWND handle, WM_MYMESSAGE,

WPARAM wParam, LPARAM lParam)

Medium:

How to obtain the first parameter?

If my message is generated in my own application, can I display some data (using the TextOut function) in the window that I want to send to the application?

(This can also be said: Use Appwizard to generate the application framework, how to obtain the window handle in the generated class (such as CView), and put it in the PostMessage function .)

3. What is the use of wParam and lParam in the message response function? How does vc ensure that these two data are transmitted to the function? There are many problems. Thank you!

Level: just getting started

Answer:

1. This is a positive question. You can use ClassWizard to define the class or manually enter it. If the class definition is already in a file, you only need to use Project | Add files to Add the file to the Project. To define class objects, you only need to define them in the corresponding events of your menu items. For example:

{

...

MyClass myObject ("Hello ");

MyObject. MyMethod ();

...

}

2. There is certainly no problem in passing messages in your own program. As long as you know that the window class to be called is inherited from CWnd, you can use the GetSafeHwnd function to obtain the window handle. However, it is too troublesome to use custom messages in the same program. You can add a member function to the class you want to call. If you want to display data, simply call this member function? Why use PostMessage? Generally, you are willing to use custom messages only for inter-program calls. In this case, you can use FindWindow to obtain the window handle (QA000251 "How to Use FindWindow () function to find the program ").

3. For messages that have defined message processing functions in MFC, MFC automatically maps wParam and lParam to a more easy-to-use method. For example, OnMouseMove (UINT nFlags, CPoint point ). For functions that cannot be automatically processed by MFC, if you use ON_MESSAGE to define the message function, MFC will pass the original wParam and lParam to your function without any processing.

=== An undisclosed Win32 API function: GetTaskmanWindow ()

In the following example, GetProcAddress GetParent (hWnd) is also used)

HMODULE hUser32 = GetModuleHandle ("user32 ");

Download

// Getaskmanwnd. cpp (Windows NT/2000)

//

// Use an undisclosed Win32 API function: GetTaskmanWindow,

// Operate the Windows taskbar (display/hide ). This function returns the window handle with the taskbar button.

//

// This example will show you how you can obtain a handle to

// Windows Taskbar window.

//

// (C) 1999 Ashot Oganesyan K, SmartLine, Inc

// Mailto: ashot@aha.ru, http://www.protect-me.com, http://www.codepile.com

# I nclude <windows. h>

# I nclude <stdio. h>

// User32! GetTaskmanWindow (NT specific !)

//

// This function returns a handle to the window that ownes the taskbar buttons

//

// HWND GetTaskmanWindow ()

//

Typedef HWND (WINAPI * PROCGETTASKMANWND) (void );

PROCGETTASKMANWND GetTaskmanWindow;

Void main (int argc, char * argv [])

{

If (argc <2)

{

Printf ("Usage: \ n \ ngetaskmanwnd.exe S | H \ n ");

Return;

}

HMODULE hUser32 = GetModuleHandle ("user32 ");

If (! HUser32)

Return;

GetTaskmanWindow = (PROCGETTASKMANWND) GetProcAddress (hUser32, "GetTaskmanWindow ");

If (! GetTaskmanWindow)

Return;

HWND hWnd = GetTaskmanWindow ();

If (! HWnd)

Return;

If (* argv [1] = "H" | * argv [1] = "h ")

ShowWindow (GetParent (hWnd), SW_HIDE );

Else

ShowWindow (GetParent (hWnd), SW_SHOW );

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.