1. Trang chủ
  2. » Công Nghệ Thông Tin

programming windows phần 4 pptx

128 242 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 128
Dung lượng 495,02 KB

Nội dung

case WM_COMMAND : if (LOWORD (wParam) == ID_LIST && HIWORD (wParam) == LBN_DBLCLK) { if (LB_ERR == (i = SendMessage (hwndList, LB_GETCURSEL, 0, 0))) break ; SendMessage (hwndList, LB_GETTEXT, i, (LPARAM) szBuffer) ; if (INVALID_HANDLE_VALUE != (hFile = CreateFile (szBuffer, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL))) { CloseHandle (hFile) ; bValidFile = TRUE ; lstrcpy (szFile, szBuffer) ; GetCurrentDirectory (MAX_PATH + 1, szBuffer) ; if (szBuffer [lstrlen (szBuffer) - 1] != `\\') lstrcat (szBuffer, TEXT ("\\")) ; SetWindowText (hwndText, lstrcat (szBuffer, szFile)) ; } else { bValidFile = FALSE ; szBuffer [lstrlen (szBuffer) - 1] = `\0' ; // If setting the directory doesn't work, maybe it's // a drive change, so try that. if (!SetCurrentDirectory (szBuffer + 1)) { szBuffer [3] = `:' ; szBuffer [4] = `\0' ; SetCurrentDirectory (szBuffer + 2) ; } // Get the new directory name and fill the list box. GetCurrentDirectory (MAX_PATH + 1, szBuffer) ; SetWindowText (hwndText, szBuffer) ; SendMessage (hwndList, LB_RESETCONTENT, 0, 0) ; SendMessage (hwndList, LB_DIR, DIRATTR, (LPARAM) TEXT ("*.*")) ; } InvalidateRect (hwnd, NULL, TRUE) ; } return 0 ; case WM_PAINT : if (!bValidFile) break ; if (INVALID_HANDLE_VALUE == (hFile = CreateFile (szFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL))) { bValidFile = FALSE ; break ; } ReadFile (hFile, buffer, MAXREAD, &i, NULL) ; CloseHandle (hFile) ; // i now equals the number of bytes in buffer. // Commence getting a device context for displaying text. This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com hdc = BeginPaint (hwnd, &ps) ; SelectObject (hdc, GetStockObject (SYSTEM_FIXED_FONT)) ; SetTextColor (hdc, GetSysColor (COLOR_BTNTEXT)) ; SetBkColor (hdc, GetSysColor (COLOR_BTNFACE)) ; // Assume the file is ASCII DrawTextA (hdc, buffer, i, &rect, DTFLAGS) ; EndPaint (hwnd, &ps) ; return 0 ; case WM_DESTROY : PostQuitMessage (0) ; return 0 ; } return DefWindowProc (hwnd, message, wParam, lParam) ; } LRESULT CALLBACK ListProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_KEYDOWN && wParam == VK_RETURN) SendMessage (GetParent (hwnd), WM_COMMAND, MAKELONG (1, LBN_DBLCLK), (LPARAM) hwnd) ; return CallWindowProc (OldList, hwnd, message, wParam, lParam) ; } This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com In ENVIRON, when we selected an environment variable either with a mouse click or with the keyboard the program displayed an environment string. If we used this select-display approach in HEAD, however, the program would be too slow because it would continually need to open and close files as you moved the selection through the list box. Instead, HEAD requires that the file or subdirectory be double-clicked. This presents a bit of a problem because list box controls have no automatic keyboard interface that corresponds to a mouse double-click. As we know, we should provide keyboard interfaces when possible. The solution? Window subclassing, of course. The list box subclass function in HEAD is named ListProc. It simply looks for a WM_KEYDOWN message with wParam equal to VK_RETURN and sends a WM_COMMAND message with an LBN_DBLCLK notification code back to the parent. The WM_COMMAND processing in WndProc uses the Windows function CreateFile to check for the selection from the list. If CreateFile returns an error, the selection is not a file, so it's probably a subdirectory. HEAD then uses SetCurrentDirectory to change the subdirectory. If SetCurrentDirectory doesn't work, the program assumes the user has selected a drive letter. Changing drives also requires a call to SetCurrentDirectory, except the preliminary dash needs to be avoided and a colon needs to be added. It sends an LB_RESETCONTENT message to the list box to clear out the contents and an LB_DIR message to fill the list box with files from the new subdirectory. The WM_PAINT message processing in WndProc opens the file using the Windows CreateFile function. This returns a handle to the file that can be passed to the Windows functions ReadFile and CloseHandle. And now, for the first time in this chapter, we encounter an issue involving Unicode. In a perfect world, perhaps, text files would be recognized by the operating system so that ReadFile could convert an ASCII file into Unicode text, or a Unicode file into ASCII text. But this is not the case. ReadFile just reads the bytes of the file without any conversion. This means that DrawTextA (in an executable compiled without the UNICODE identifier defined) would interpret the text as ASCII and DrawTextW (in the Unicode version) would assume the text is Unicode. So what the program should really be doing is trying to figure out whether the file has ASCII text or Unicode text and then calling DrawTextA or DrawTextW appropriately. Instead, HEAD takes a much simpler approach and uses DrawTextA regardless. This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Chapter 10 Menus and Other Resources Most Microsoft Windows programs include a customized icon that Windows displays in the upper left corner of the title bar of the application window. Windows also displays the program's icon when the program is listed in the Start menu, shown in the taskbar at the bottom of the screen, listed in the Windows Explorer, or shown as a shortcut on the desktop. Some programs most notably graphical drawing tools such as Windows Paint use customized mouse cursors to represent different operations of the program. Many Windows programs use menus and dialog boxes. Along with scroll bars, menus and dialog boxes are the bread and butter of the Windows user interface. Icons, cursors, menus, and dialog boxes are all related. They are all types of Windows "resources." Resources are data and they are often stored in a program's .EXE file, but they do not reside in the executable program's data area. In other words, the resources are not immediately addressable by variables in the program's code. Instead, Windows provides functions that explicitly or implicitly load a program's resources into memory so that they can be used. We've already encountered two of these functions. They are LoadIcon and LoadCursor, and they have appeared in the sample programs in the assignment statements that define a program's window class structure. So far, these functions have loaded a binary icon or cursor image from within Windows and returned a handle to that icon or cursor. In this chapter, we'll begin by creating our own customized icons that are loaded from the program's own .EXE file. This book covers these resources: • Icons • Cursors • Character strings • Custom resources • Menus • Keyboard accelerators • Dialog boxes • Bitmaps The first six resources in the list are discussed in this chapter. Dialog boxes are covered in Chapter 11 and bitmaps in Chapter 14. This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Icons, Cursors, Strings, and Custom Resources One of the benefits of using resources is that many components of a program can be bound into the program's .EXE file. Without the concept of resources, a binary file such as an icon image would probably have to reside in a separate file that the .EXE would read into memory to use. Or the icon would have to be defined in the program as an array of bytes (which might make it tough to visualize the actual icon image). As a resource, the icon is stored in a separate editable file on the developer's computer but is bound into the .EXE file during the build process. Adding an Icon to a Program Adding resources to a program involves using some additional features of Visual C++ Developer Studio. In the case of icons, you use the Image Editor (also called the Graphics Editor) to draw a picture of your icon. This image is stored in an icon file with an extension .ICO. Developer Studio also generates a resource script (that is, a file with the extension .RC, sometimes also called a resource definition file) that lists all the program's resources and a header file (RESOURCE.H) that lets your program reference the resources. So that you can see how these new files fit together, let's begin by creating a new project, called ICONDEMO. As usual, in Developer Studio you pick New from the File menu, select the Projects tab, and choose Win32 Application. In the Project Name field, type ICONDEMO and click OK. At this point, Developer Studio creates five files that it uses to maintain the workspace and the project. These include the text files ICONDEMO.DSW, ICONDEMO.DSP, and ICONDEMO.MAK (assuming you've selected "Export makefile when saving project file" from the Build tab of the Options dialog box displayed when you select Options from the Tools menu). Now let's create a C source code file as usual. Select New from the File menu, select the Files tab, and click C++ Source File. In the File Name field, type ICONDEMO.C and click OK. At this point, Developer Studio has created an empty ICONDEMO.C file. Type in the program shown in Figure 10-1, or pick the Insert menu and then the File As Text option to copy in the source code from this book's companion CD-ROM. Figure 10-1. The ICONDEMO program. This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ICONDEMO.C /* ICONDEMO.C Icon Demonstration Program (c) Charles Petzold, 1998 */ #include <windows.h> #include "resource.h" LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ; int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { TCHAR szAppName[] = TEXT ("IconDemo") ; 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 (hInstance, MAKEINTRESOURCE (IDI_ICON)) ; wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ; wndclass.hbrBackground = 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, TEXT ("Icon Demo"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL) ; ShowWindow (hwnd, iCmdShow) ; UpdateWindow (hwnd) ; while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg) ; DispatchMessage (&msg) ; } return msg.wParam ; } This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { static HICON hIcon ; static int cxIcon, cyIcon, cxClient, cyClient ; HDC hdc ; HINSTANCE hInstance ; PAINTSTRUCT ps ; int x, y ; switch (message) { case WM_CREATE : hInstance = ((LPCREATESTRUCT) lParam)->hInstance ; hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_ICON)) ; cxIcon = GetSystemMetrics (SM_CXICON) ; cyIcon = GetSystemMetrics (SM_CYICON) ; return 0 ; case WM_SIZE : cxClient = LOWORD (lParam) ; cyClient = HIWORD (lParam) ; return 0 ; case WM_PAINT : hdc = BeginPaint (hwnd, &ps) ; for (y = 0 ; y < cyClient ; y += cyIcon) for (x = 0 ; x < cxClient ; x += cxIcon) DrawIcon (hdc, x, y, hIcon) ; EndPaint (hwnd, &ps) ; return 0 ; case WM_DESTROY : PostQuitMessage (0) ; return 0 ; } return DefWindowProc (hwnd, message, wParam, lParam) ; } This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com If you try compiling this program, you'll get an error because the RESOURCE.H file referenced at the top of the program does not yet exist. However, you do not create this RESOURCE.H file directly. Instead, you let Developer Studio create it for you. You do this by adding a resource script to the project. Select New from the File menu, select the Files tab, click Resource Script, and type ICONDEMO in the File Name field. Click OK. At this time, Developer Studio creates two new text files: ICONDEMO.RC, the resource script, and RESOURCE.H, a header file that will allow the C source code file and the resource script to refer to the same defined identifiers. Don't try to edit these two files directly; let Developer Studio maintain them for you. If you want to take a look at the resource script and RESOURCE.H without any interference from Developer Studio, try loading them into Notepad. Don't change them there unless you really know what you're doing. Also, keep in mind that Developer Studio will save new versions of these files only when you explicitly direct it to or when it rebuilds the project. The resource script is a text file. It contains text representations of those resources that can be expressed in text, such as menus and dialog boxes. The resource script also contains references to binary files that contain nontext resources, such as icons and customized mouse cursors. Now that RESOURCE.H exists, you can try compiling ICONDEMO again. Now you get an error message indicating that IDI_ICON is not defined. This identifier occurs first in the statement wndclass.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_ICON)) ; That statement in ICONDEMO has replaced this statement found in previous programs in this book: wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ; It makes sense that we're changing this statement because we've been using a standard icon for our applications and our goal here is to use a customized icon. So let's create an icon. In the File View window of Developer Studio, you'll see two files listed now ICONDEMO.C and ICONDEMO.RC. When you click ICONDEMO.C, you can edit the source code. When you click ICONDEMO.RC, you can add resources to that file or edit an existing resource. To add an icon, select Resource from the Insert menu. Click the resource you want to add, which is Icon, and then click the New button. You are now presented with a blank 32-pixel-by-32-pixel icon that is ready to be colored. You'll see a floating toolbar with a collection of painting tools and a bunch of available colors. Be aware that the color toolbar includes two options that are not exactly colors. These are sometimes referred to as "screen" and "inverse screen." When a pixel is colored with "screen," it is actually transparent. Whatever surface the icon is displayed against will show through. This allows you to create icons that appear to be nonrectangular. Before you get too far, double-click the area surrounding the icon. You'll get an Icon Properties dialog box that allows you to change the ID of the icon and its filename. Developer Studio will probably have set the ID to IDI_ICON1. Change that to IDI_ICON since that's how ICONDEMO refers to the icon. (The IDI prefix stands for "id for an icon.") Also, change the filename to ICONDEMO.ICO. For now, I want you to select a distinctive color (such as red) and draw a large B (standing for "big") on this icon. It doesn't have to be as neat as Figure 10-2. This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 10-2. The standard (32 32) ICONDEMO file as displayed in Developer Studio. The program should now compile and run fine. Developer Studio has put a line in the ICONDEMO.RC resource script that equates the icon file (ICONDEMO.ICO) with an identifier (IDI_ICON). The RESOURCE.H header file contains a definition of the IDI_ICON identifier. (We'll take a look at this in more detail shortly.) Developer Studio compiles resources by using the resource compiler RC.EXE. The text resource script is converted into a binary form, which is a file with the extension .RES. This compiled resource file is then specified along with .OBJ and .LIB files in the LINK step. This is how the resources are added to the final .EXE file. When you run ICONDEMO, the program's icon is displayed in the upper left corner of the title bar and in the taskbar. If you add the program to the Start Menu, or if you add a shortcut on your desktop, you'll see the icon there as well. ICONDEMO also displays the icon in its client area, repeated horizontally and vertically. Using the statement hIcon = LoadIcon (hInstance, MAKEINTRESOURCE (IDI_ICON)) ; the program obtains a handle to the icon. Using the statements cxIcon = GetSystemMetrics (SM_CXICON) ; cyIcon = GetSystemMetrics (SM_CYICON) ; it obtains the size of the icon. The program can then display the icon with multiple calls to DrawIcon (hdc, x, y, hIcon) ; where x and y are the coordinates of where the upper left corner of the displayed icon is positioned. With most video display adapters in current use, GetSystemMetrics with the SM_ CXICON and SM_CYICON indices will report that the size of an icon is 32 by 32 pixels. This is the size of the icon that we created in the Developer Studio. It is also the size of the icon as it appears on the desktop and the size of the icon displayed in the client area of the ICONDEMO program. It is not, however, the size of the icon displayed in the program's title bar or in the taskbar. That smaller icon size can be obtained from GetSystemMetrics with the SM_CXSMSIZE and SM_CYSMSIZE indices. (The first "SM" means "system metrics"; the embedded "SM" means "small.") For most display adapters in current use, the small icon size is 16 by 16 pixels. This can be a problem. When Windows reduces a 32-by-32 icon to a 16-by-16 size, it must eliminate every other This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com row and column of pixels. For some complex icon images, this might cause distortions. For this reason, you should probably create special 16-by-16 icons for images where shrinkage is undesirable. Above the icon image in Developer Studio is a combo box labeled Device. To the right of that is a button. Pushing the button invokes a New Icon Image dialog box. Select Small (16x16). Now you can draw another icon. For now, use an S (for "small") as shown in Figure 10-3. Figure 10-3. The small (16 16) ICONDEMO file as displayed in Developer Studio. There's nothing else you need to do in the program. The second icon image is stored in the same ICONDEMO.ICO file and referenced with the same INI_ICON identifier. Windows will now automatically use the smaller icon when it's more appropriate, such as in the title bar and the taskbar. Windows uses the large image when displaying a shortcut on the desktop and when the program calls DrawIcon to adorn its client area. Now that we've mastered the practical stuff, let's take a closer look at what's going on under the hood. Getting a Handle on Icons If you take a look ICONDEMO.RC and RESOURCE.H, you'll see a bunch of stuff that Developer Studio generates to help it maintain the files. However, when the resource script is compiled, only a few lines are important. These critical excerpts from the ICONDEMO.RC and RESOURCE.H files are shown in Figure 10-4. ICONDEMO.RC (excerpts) //Microsoft Developer Studio generated resource script. #include "resource.h" #include "afxres.h" ///////////////////////////////////////////////////////////////////////////// // Icon IDI_ICON ICON DISCARDABLE "icondemo.ico" RESOURCE.H (excerpts) // Microsoft Developer Studio generated include file. // Used by IconDemo.rc #define IDI_ICON 101 Figure 10-4. Excerpts from the ICONDEMO.RC and RESOURCE.H files. Figure 10-4 shows ICONDEMO.RC and RESOURCE.H files that look much like they would look if you were creating them manually in a normal text editor, just as Windows programmers did in the old days way back in the 1980s. The only real difference is the presence of AFXRES.H, which is a header file that includes many common identifiers used by Developer Studio when creating machine-generated MFC projects. I will not make use of AFXRES.H in this book. This line in ICONDEMO.RC, This document is created with the unregistered version of CHM2PDF Pilot Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... IDM_EDIT_CLEAR IDM_BKGND_WHITE IDM_BKGND_LTGRAY IDM_BKGND_GRAY IDM_BKGND_DKGRAY IDM_BKGND_BLACK IDM_TIMER_START IDM_TIMER_STOP IDM_APP_HELP IDM_APP_ABOUT 40 001 40 002 40 003 40 0 04 40005 40 006 40 007 40 008 40 009 40 010 40 011 40 012 40 013 40 0 14 40015 40 016 40 017 40 018 40 019 The MENUDEMO.RC resource script should give you hints on defining the menu The menu has a text name of "MenuDemo." Most items have underlined... popup is displayed • MF_POPUP Popup is displayed • MF_SYSMENU System menu popup is displayed Windows programs usually pass this message to DefWindowProc, which normally returns a 0 to Windows, which causes Windows to beep We'll see a use for the WM_MENUCHAR message in the GRAFMENU program shown in Chapter 14 A Sample Program Let's look at a simple example The MENUDEMO program, shown in Figure 10-6,... important part of the consistent user interface that Windows programs offer, and adding a menu to your program is a relatively easy part of Windows programming You define the menu in Developer Studio Each selectable menu item is given a unique ID number You specify the name of the menu in the window class structure When the user chooses a menu item, Windows sends your program a WM_COMMAND message containing... those in other Windows programs One of the objectives of Windows is to provide a user with a recognizable interface that does not require relearning basic concepts for each program It certainly helps if the File and Edit menus look the same in every Windows program and use the same letters for selection in combination with the Alt key Beyond the File and Edit popups, the menus of most Windows programs... can type an ampersand (&) to indicate that the following character is to be underlined when Windows displays the menu Such an underlined character is the character Windows searches for when you select a menu item using the Alt key If you don't include an ampersand in the text, no underline will appear, and Windows will instead use the first letter of the menu item's text for Alt-key searches If you... Custom Resource (c) Charles Petzold, 1998 -*/ #include #include "resource.h" LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ; HINSTANCE hInst ; int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { TCHAR szAppName [16], szCaption [ 64] , szErrMsg [ 64] ; HWND hwnd ; MSG msg ; WNDCLASS wndclass ; LoadString (hInstance, IDS_APPNAME,... POEPOEM under Windows 98, these two function calls will fail Despite the fact that LoadStringA is more complex than LoadStringW (because LoadStringA must convert the resource string from Unicode to ANSI, while LoadStringW just loads it directly), LoadStringW is not one of the few string functions that is supported under Windows 98 This means that when the RegisterClassW function fails under Windows 98,... LoadIcon (hInstance, MAKEINTRESOURCE (125)) ; The obscure method is this: hIcon = LoadIcon (hInstance, TEXT ("#125")) ; Windows recognizes the initial # character as prefacing a number in ASCII form Using Icons in Your Program Although Windows uses icons in several ways to denote a program, many Windows programs specify an icon only when defining the window class with the WNDCLASS structure and RegisterClass... created based on this class, the customized cursor associated with IDC_CURSOR or szCursor will be displayed If you use child windows, you may want the cursor to appear differently, depending on the child window below the cursor If your program defines the window class for these child windows, you can use different cursors for each class by appropriately setting the hCursor field in each window class And... another, and another (eventually totaling about 40 types, most of which are quite obscure), and still the answer is "No, no, no, no, no." Ultimately, there's a shooting involved This whole unfortunate incident could have been avoided through the use of menus A menu is a list of available options A menu tells a hungry patron what the kitchen can serve up and for a Windows program tells the user what operations . Other Resources Most Microsoft Windows programs include a customized icon that Windows displays in the upper left corner of the title bar of the application window. Windows also displays the program's. ("#125")) ; Windows recognizes the initial # character as prefacing a number in ASCII form. Using Icons in Your Program Although Windows uses icons in several ways to denote a program, many Windows. the bottom of the screen, listed in the Windows Explorer, or shown as a shortcut on the desktop. Some programs most notably graphical drawing tools such as Windows Paint use customized mouse cursors

Ngày đăng: 13/08/2014, 08:20

TỪ KHÓA LIÊN QUAN