Visual c ++ programming skills (I)

Source: Internet
Author: User
1. How can I obtain the instance handle of an application?

The instance handle of the application is stored in cwinappim_hinstance.

Afxgetinstancdhandle to get the handle.

Example: handle hinstance = AfxGetInstanceHandle ();

2. How to get the pointer to the main window of the application through code?

The pointer of the main window is saved in cwinthread: m_pmainwnd, And the afxgetmainwnd implementation is called.

Afxgetmainwnd ()-> showwindow (sw_showmaxmized); // maximize the program.

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

Two methods:

(1) Use the SDK function shgetfileinfo or use extracticon to obtain the 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 =: extracticon (AfxGetInstanceHandle (), _ t

("Notepad.exe"), 0 );

If (hicon & hicon! = (Hicon)-1)

PDC-> drawicon (10, 10, hicon );

}

Note: The paths of notepad.exe are generally obtained using the getwindowsdirectory function. If you call the paint brush under Win95, you should use the method of accessing the registry to obtain the path and create a more sophisticated program, the considerations should be comprehensive.

4. How to program and end the application? How can I control windows reboot by programming?

This is very simple and a common problem in programming.

First, send the wm_close message to the window and call the cwnd: onclose member function. The user can be prompted.

Whether to save the modified data.

Example: afxgetmainwindow ()-> sendmessage (wm_close );

You can also create a custom function terminate window.

Void terminate window (lpcstr pcaption)

{

Cwnd * pwnd = cwnd: findwindow (null, pcaption );

If (pwnd)

Pwnd-> sendmessage (wm_close );

}

Note: The findwindow function is not recommended because it cannot automatically change the title bar. For example, if we want to check whether notepad is running and do not know the title bar of notepad beforehand, findwindow will be powerless, you can do this by enumerating the Windows task list. I have a detailed introduction in the book "Windows 95 API developer Guide" by mechanical Publishing House.

The second question is whether the use exitwindowsex function control system is a reboot or a restart of windows. If you have mentioned this before, you will not mention it again.

5. How to add other applications?

I remember it was a high frequency of appearance.

Three SDK functions are available: winexec, ShellExecute, and CreateProcess.

Winexec is the simplest. It has two parameters: Specify the path before and specify the display mode after. the next parameter is worth mentioning. For example, if the mud uses sw_showmaxmized to add a program without the maximum button, such as neterm and calc, the normal form will not appear, but it has been added to the task list. ShellExecute is a little more flexible than winexex. You can specify a working directory. The following example is to directly open C:/temp/1.txtwithout planting the application associated with the TXT file, after many installation programs are completed, a window will be opened to display readme or FAQ. I guess that's exactly what it is.

ShellExecute (null, null, _ T ("1.txt"), null, _ T (" C: // Temp "), sw_showmaxmized );

CreateProcess is the most complex. It has a total of ten parameters, but most of them can be replaced by null. It can specify the process's security attributes, Inheritance Information, class priority, and so on. Let's look at a very simple example:

Startupinfo stinfo; // start window information

Processinfo procinfo; // Process Information

CreateProcess (null, _ T ("notepad.exe"), null, null. False, normal_priority _

Class, null, null, & stinfo, & procinfo );

6. Determine the Application Path

Someone seems to have asked this question a few days ago.

Use getmodulefilename to obtain the application path, and then remove the executable file name.

Example:

Tchar exefullpath [max_path]; // max_path is defined in the API, as if 128

Getmodulefilename (null, exefullpath, max_path)

7. obtain various directory information

Windows Directory: Use "getwindowsdirectory"

System Directory in Windows: Use "getsystemdirectory"

Temp Directory: Use "gettemppath"

Current Directory: Use "getcurrentdirectory"

Note that the first parameter of the first two functions is the directory variable name, the last is the buffer, and the last two are opposite.

8. How to customize messages

Some people have asked, but it is not difficult.

(1) manually define the message, so you can write # define wm_my_message (wm_user + 100 ),

The MS recommends at least wm_user + 100;

(2) write the message processing function and use wparam and lparam to return lresult.

Lresult cmainframe: onmymessage (wparam, lparam)

{

// Add your handler

}

(3) declare in afx_msg of the class, that is, macro ing"

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

The instance handle of the application is stored in cwinappim_hinstance.

Afxgetinstancdhandle to get the handle.

Example: handle hinstance = AfxGetInstanceHandle ();

2. How to get the pointer to the main window of the application through code?

The pointer of the main window is saved in cwinthread: m_pmainwnd, And the afxgetmainwnd implementation is called.

Afxgetmainwnd ()-> showwindow (sw_showmaxmized); // maximize the program.

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

Two methods:

(1) Use the SDK function shgetfileinfo or use extracticon to obtain the 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 =: extracticon (AfxGetInstanceHandle (), _ t

("Notepad.exe"), 0 );

If (hicon & hicon! = (Hicon)-1)

PDC-> drawicon (10, 10, hicon );

}

Note: The paths of notepad.exe are generally obtained using the getwindowsdirectory function. If you call the paint brush under Win95, you should use the method of accessing the registry to obtain the path and create a more sophisticated program, the considerations should be comprehensive.

4. How to program and end the application? How can I control windows reboot by programming?

This is very simple and a common problem in programming.

First, send the wm_close message to the window and call the cwnd: onclose member function. The user can be prompted.

Whether to save the modified data.

Example: afxgetmainwindow ()-> sendmessage (wm_close );

You can also create a custom function terminate window.

Void terminate window (lpcstr pcaption)

{

Cwnd * pwnd = cwnd: findwindow (null, pcaption );

If (pwnd)

Pwnd-> sendmessage (wm_close );

}

Note: The findwindow function is not recommended because it cannot automatically change the title bar. For example, if we want to check whether notepad is running and do not know the title bar of notepad beforehand, findwindow will be powerless, you can do this by enumerating the Windows task list. I have a detailed introduction in the book "Windows 95 API developer Guide" by mechanical Publishing House.

The second question is whether the use exitwindowsex function control system is a reboot or a restart of windows. If you have mentioned this before, you will not mention it again.

5. How to add other applications?

I remember it was a high frequency of appearance.

Three SDK functions are available: winexec, ShellExecute, and CreateProcess.

Winexec is the simplest. It has two parameters: Specify the path before and specify the display mode after. the next parameter is worth mentioning. For example, if the mud uses sw_showmaxmized to add a program without the maximum button, such as neterm and calc, the normal form will not appear, but it has been added to the task list. ShellExecute is a little more flexible than winexex. You can specify a working directory. The following example is to directly open C:/temp/1.txtwithout planting the application associated with the TXT file, after many installation programs are completed, a window will be opened to display readme or FAQ. I guess that's exactly what it is.

ShellExecute (null, null, _ T ("1.txt"), null, _ T (" C: // Temp "), sw_showmaxmized );

CreateProcess is the most complex. It has a total of ten parameters, but most of them can be replaced by null. It can specify the process's security attributes, Inheritance Information, class priority, and so on. Let's look at a very simple example:

Startupinfo stinfo; // start window information

Processinfo procinfo; // Process Information

CreateProcess (null, _ T ("notepad.exe"), null, null. False, normal_priority _

Class, null, null, & stinfo, & procinfo );

6. Determine the Application Path

Someone seems to have asked this question a few days ago.

Use getmodulefilename to obtain the application path, and then remove the executable file name.

Example:

Tchar exefullpath [max_path]; // max_path is defined in the API, as if 128

Getmodulefilename (null, exefullpath, max_path)

7. obtain various directory information

Windows Directory: Use "getwindowsdirectory"

System Directory in Windows: Use "getsystemdirectory"

Temp Directory: Use "gettemppath"

Current Directory: Use "getcurrentdirectory"

Note that the first parameter of the first two functions is the directory variable name, the last is the buffer, and the last two are opposite.

8. How to customize messages

Some people have asked, but it is not difficult.

(1) manually define the message, so you can write # define wm_my_message (wm_user + 100 ),

The MS recommends at least wm_user + 100;

(2) write the message processing function and use wparam and lparam to return lresult.

Lresult cmainframe: onmymessage (wparam, lparam)

{

// Add your handler

}

(3) declare in afx_msg of the class, that is, macro ing"
9. How do I change the window icon?

Send the wm_section message to the window.

Example:

Hicon = afxgetapp ()-> loadicon (idi_icon );

Assert (hicon );

Afxgetmainwnd ()-> sendmessage (wm_section, true, (lparam) hicon );

10. How can I change the default window style?

Resend cwnd: precreatewindow and modify the createstruct structure to specify the window style and other

Create information.

Example: Delete "Max" button and set original window's position and size

Bool cmainframe: precreatewindow (createstruct & CS)

{

CS. Style & = ~ Ws_maxinizemox;

CS. x = cs. Y = 0;

CS. Cx = getsystemmetrics (sm_cxscreen/2 );

CS. Cy = getsystemmetrics (sm_cyscreen/2 );

Return cmdiframewnd: precreatewindow (CS );

}

11. How to center the window display?

Easy, call function cwnd: center windows

Example (1): center window (); // relative to it's parent

// Relative to screen

Example (2): center window (cwnd: getdesktopwindow ());

// Relative to application's mainwindow

Afxgetmainwnd ()-> center window ();

12. How can I maximize and minimize windows and MDI windows as soon as they are started?

Let's talk about the window first.

Set the m_ncmdshow value in the initstance function.

M_ncmdshow = sw_showmaxmized; // maximize

M_ncmdshow = sw_showminmized; // minimized

M_ncmdshow = sw_shownormal; // Normal Mode

MDI window:

If you are creating a new application, you can use the advanced button of the MFC Appwizard and

Maximize or minimize the detection in the MDI child window style group. You can also reload

Precreatewindow function, set ws_maxmize or ws_minmize;

If it is derived from cmdichildwnd, call cwnd: Show in oninitialupdate Function

Window to specify the style of the MDI child window.

13. How to keep the program in a very small state?

Interesting question

In this case, Windows will send a WM_QUERY-OPEN message when the form of the Recovery Program is large,

Use classwizard to set the member function onqueryopen (), add following code:

Bool cmainframe: onqueryopen ()

{

Return false;

}

14. How do I limit the window size?

That is, the fixeddialog format. Windows sends wm_getmaxmininfo messages for tracking,

Respond to it and write the code in ongetmaxmininfo:

15. How to Make the window invisible?

It is easy to hide the window with sw_hide. You can use findwindow and showwindow to control the window.

16. How to keep the window at the forefront?

There are two ways.

Bringwindowtotop (handle );

Setwindowpos function, which specifies the top style of the window. Use ws_ex_topmost to extend the window style.

Example:

Void toggletopmost (cwnd * pwnd)

{

Assert_valid (pwnd );

Pwnd-> setwindowpos (pwnd-> getstyle () & ws_ex_topmost )?

& Wndnotopmost: & wndtopmost, 0, 0, 0, ssp_nosize | wsp_nomove );

}

17. How to Create ceditview

Reload the cwnd: precreatewindow and modify the createstruct structure to disable the es_autohscroll and ws_hscroll style bits of the ceditview object. Because the ceditview: precreatewindow display sets CS. style. After the base class function is called, modify the CS. style.

Bool csampleeditview: precreatewindow (createstruct & CS)

{

// First call Basse class function.

Bool bresul = ceditview: precreatewindow (CS );

// Now specify the new window style.

CS. Style & = ~ (Es_autohscroll | ws_hscroll );

Return bresult;

}

18. display window of common controls

MFC provides several windows classes derived from cview, which encapsulate the functions of common controls, but still uses

Window architecture: ceditview encapsulates the editing control and ctreeview maintains the tree list.

Controls. clistview encapsulates the list display window controls. cricheditview can process multiple editing controls.

19. Move the window

Call cwnd: setwindowpos and specify the swp_nosize flag. Target Location and parent window

Related (the top-level window is related to the screen ). You must specify the window when calling cwnd: movewindow.

.

// Move window to positoin 100,100 of its parent window.

Setwindowpos (null, 100,100, 0, 0, swp_nosize | swp_noaorder );

20. Reset the window size.

Call cwnd: setwindowpos and specify the swp_nomove flag.

Cwnd: movewindow, but the position of the window must be specified.

// Get the size of the window.

Crect rewindow;

Getwindowrect (rewindow );

// Make the window twice as wide and twice as tall.

Setwindowpos (null, 0, 0, rewindow. Width () * 2,

Rewindow. Height () * 2,

Swp_nomove | swp_nozorder );

21. How to move the window by clicking an area other than the window title bar

Windows sends wm_nchittest information to the window to determine the mouse position.

This information makes windows think that the mouse is on the window title. For dialog box and dialog-based applications, you can

To use classwizard to process the information and call the base class function. If the function returns htclient, it indicates

Move the mouse in the room area. If you return htcaption, the mouse is in the title bar of windows.

Uint csampledialog: onnchittest (cpoint point)

{

Uint nhittest = cdialog: onnchittest (point );

Return (nhittest = htclient )? Htcaption: nhittest;

}

The above two technologies have two disadvantages. One is that when you double-click the customer area in the window, the window will be extremely large;

Second, it is not suitable for the main window that contains several windows. You can also use the left mouse button

Make the main box window think that the mouse is on its window title, use classwizard to process wm_lbuttodown in the window

And send a wm_nclbuttondown message and a click test htcaption message to the main window.

Void csampleview: onlbuttondown (uint nflags, cpoint point)

{

Cview: onlbuttondow (nflags, Pont );

// Fool frame window into thinking somene clicked on

Its caption bar.

Getparentframe ()-> postmessage (

Wm_nclbuttondown, htcaption, makelparam (poitn. X, point. y ));

}

This technique is also applicable to dialog boxes and peer-based applications, but does not need to call cwnd: getparentframe.

Void csampledialog: onlbuttondown (uint nflags, cpoint point)

{

Cdialog: onlbuttondow (nflags, goint );

// Fool dialog into thinking simeone clicked on its caption bar.

Postmessage (wm_nclbuttondown, htcaption, makelparm (point. X, point. y ))

}

22. How to change the background color of a window

Windows sends a wm_erasebkgnd message to the window to notify the window to erase the background. You can use

Classwizard reloads the default handler of the message to erase the background (actually painted), and returns true

Prevents Windows from erasing windows.

// Paint area that needs to be erased.

Bool csampleview: onerasebkgnd (CDC * PDC)

{

// Create a pruple brush.

Cbrush brush (RGB (128, 0,128 ));

// Select the brush into the device context.

Cbrush * poldbrush = PDC-> selcetobject (& brush );

// Get the area that needs to be erased.

Crect reclip;

PDC-> getcilpbox (& rcclip );

// Paint the area.

PDC-> patblt (rcclip. Left, rcclip. Top,

Rcclip. Width (), rcclip. Height (), patcopy );

// Unselect brush out of device context.

PDC-> SelectObject (poldbrush );

// Return nonzero to half fruther processing.

Return true;

}

23. How to change the window title

You can call cwnd: setwindowtext to change the title of any window (including controls.

// Set title for application's main frame window.

Afxgetmainwnd ()-> setwindowtext (_ T ("application title "));

// Set title for view's MDI child frame window.

Getparentframe ()-> setwindowtext ("_ T (" MDI child frame new title "));

// Set title for dialog's push button control.

Getdigitem (idc_button)-> setwindowtext (_ T ("button New title "));

If you need to modify the title of the window frequently (note: the control is also a window), you should consider using semi-docalized

Function afxsetwindowtext. In afxpriv. H, this function is implemented in winutil. cpp.

It cannot be found in online help. It is semi-documented in afxpriv. h and documented in later releases of MFC.

Afxsetwindowtext is implemented as follows:

Voik afxapi afxsetwindowtext (hwnd hwndctrl, lpctstr ipsznew)

{

ITN nnewlen = istrlen (ipaznew );

Tchar Szold [256];

// Fast check to see if text really changes (reduces flash in the controls)

If (nnewlen> _ contof (Szold) |

: Getwindowtext (hwndcrtl, Szold, _ countof (Szold )! = Nnewlen |

Istrcmp (Szold, ipsznew )! = 0

{

// Change it

: Setwindowtext (hwndctrl, ipsznew );

}

}

24. How to Prevent the main window from displaying the active document name in its description

Create a primary box window and an MDI sub-window with the fws_addtotitle style bits. If you do not want

This style bit must be disabled and can be reset using classwizard.

Cwnd: precreatewindow and disable the fws_addtotitle style.

Bool cmainframe: precreatewindow (createstruct & CS)

{

// Turn off fws_addtotitle in main frame.

CS. styel & = ~ Fws_addtotitle;

Return cmdiframewnd: precreatewindow (CS );

}

Close the FWS _ addtotitle style of the MDI subwindow to create a window with an empty title. You can call

Use cwnd: setwindowtext to set the title. Remember to follow the interface style guide when setting the title.

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.