CS410 – Visual Programming: Midterm Important Subjective (57 Solved Q&As)
Computer Science • Read every solved subjective question with its model answer directly on this page. Free, no login required.
All 664 Midterm Packs · CS410 Course Page · CS410 MCQ Pack (157 MCQs)
-
What are macros? Discuss their types with examples.
Topic: C Language and Preprocessor
A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros: 1. Object-like macros — they resemble data objects when used, e.g. #define PI 3.14159 2. Function-like macros — they resemble function calls, e.g. a macro that computes the maximum of two numeric values: #define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) To define a macro that takes arguments, the #define command is used with a list of parameters in parentheses after the name of the macro. The parameters may be any valid C identifiers separated by commas, and the left parenthesis must follow the macro name immediately, with no space in between.
-
Define typedef with an example.
Topic: C Language and Preprocessor
A typedef declaration lets you define your own identifiers that can be used in place of type specifiers such as int, float and double. The names defined using typedef are NOT new data types; they are synonyms for the data types (or combinations of data types) they represent. For example: typedef int LENGTH; LENGTH length, width, height; These statements declare LENGTH as a synonym for int and then use it to declare length, width and height as integer variables.
-
Write the names of the two types of implicit type conversion.
Topic: C Language and Preprocessor
Implicit type casting (coercion) is further divided into two types: 1. Promotion — conversion of a smaller data type into a larger data type, e.g. int to float. 2. Demotion — conversion of a larger data type into a smaller data type, e.g. float to int.
-
Explain pointer to constant and constant pointer.
Topic: C Language and Preprocessor
Variable pointer to constant data: const char * ptr = buff; // variable pointer to constant data *ptr = 'a'; // it will be an error ptr = buff2; // allowed Here the data to which ptr points remains constant and cannot be modified, but the contents of ptr (the address it holds) are variable and can be changed. Constant pointer to variable data: char * const ptr = buff; // constant pointer to variable data *ptr = 'a'; // allowed ptr = buff2; // it will be an error Here ptr is a constant pointer, so the address stored in it cannot be modified, but the data it points to can be changed.
-
Name the types of assertion and explain them briefly.
Topic: C Language and Preprocessor
There are three types of assertion: 1. Preconditions — specify conditions at the start of a function. 2. Postconditions — specify conditions at the end of a function. 3. Invariants — specify conditions over a defined region of a program.
-
What is the difference between __stdcall and __cdecl calling conventions?
Topic: C Language and Preprocessor
The calling convention tells the compiler whether the called function or the calling function cleans up the stack. In the __stdcall calling convention, the called function cleans up the stack when it is about to return, so the call sites do not need extra code to clean up the stack after the call. In the __cdecl calling convention, the caller function is responsible for cleaning the stack, so every function call must include extra code to clean up the stack after the function call. __cdecl is the default calling convention for C programs and creates larger executables than __stdcall.
-
According to the __cdecl calling convention, state the argument passing order, the stack maintenance responsibility and the name-decoration convention.
Topic: C Language and Preprocessor
1. Argument order: Right to left. 2. Stack maintenance responsibility: The calling function pops the arguments from the stack (caller cleans the stack). 3. Name-decoration convention: An underscore (_) is used as a prefix to the function name.
-
What is the extern storage class?
Topic: C Language and Preprocessor
The extern storage class defines a global variable that is visible to all object modules. When 'extern' is used, the variable cannot be initialized, because all it does is point the variable name at a storage location that has been previously defined.
-
Describe WinMain in detail. Also write its four parameters.
Topic: Windows Programming Basics
WinMain is the starting point (entry point) of every Win32 GUI program. It has four parameters: 1. The instance handle of the current application. 2. The instance handle of the previous instance of the same application already running. It was used only in 16-bit Windows (Windows 3.1); 32-bit editions do not support this parameter and it is present only for compatibility (always NULL in Win32). 3. The command line argument, a string of type char * (LPSTR). 4. The window display state (nCmdShow), which specifies how the window is to be shown, e.g. SW_SHOW, SW_SHOWMAXIMIZED.
-
Microsoft Windows consists of three important components. Name them and state the responsibility of each.
Topic: Windows Programming Basics
1. Kernel — the main module of the operating system; it provides system services for managing threads, memory and resources (process management, file management and memory management). 2. User — provides the functionality to create and manage screen windows and most basic controls, and handles user input. 3. GDI (Graphics Device Interface) — the subsystem responsible for displaying text and images on display devices and printers.
-
What are handles? Name three basic types of handles in Windows programming.
Topic: Windows Programming Basics
A handle is a unique value (a 32-bit number) that Windows uses to identify and refer to an object or resource created or managed by the system, such as a window, an application instance, a device context, a menu, a file or a GDI object. The application does not access the object directly; it uses the handle in API function calls. Three basic types of handles are: 1. HWND — handle to a window. 2. HINSTANCE — handle to an application instance. 3. HDC — handle to a device context.
-
How does Windows keep track of the files (modules)?
Topic: Windows Programming Basics
The system requires instance handles to keep track of all modules. The system assigns a handle to each copy of a running executable or DLL, so every loaded module is identified by its instance handle.
-
Name any five elements included in an application window.
Topic: Windows Programming Basics
An application window includes elements such as: a title bar, a menu bar, the window menu (formerly known as the system menu), the minimize button, the maximize button, the restore button, the close button, a sizing border, a client area, a horizontal scroll bar and a vertical scroll bar. (Any five of these.)
-
Differentiate between the desktop window and an application window.
Topic: Windows Programming Basics
Desktop window: When the system is started, it automatically creates the desktop window. It is a system-defined window and uses a bitmap to paint the background of the screen. A system configuration application, such as a Control Panel item, changes the desktop wallpaper by using the SystemParametersInfo function. Application window: When an application is started, the system associates a taskbar button with it, containing the program icon and title. Most applications also create other windows, directly or indirectly, to perform tasks related to the main window. An application window includes elements such as a title bar, a menu bar, the window menu, minimize/maximize/close buttons and a client area.
-
Define the client area of a window.
Topic: Windows Programming Basics
The client area is the part of a window where the application displays output, such as text or graphics. For example, a desktop publishing application displays the current page of a document in the client area. The application must provide a function, called a window procedure, to process input to the window and display output in the client area.
-
"A window may have more than one window inside it." Explain this line.
Topic: Windows Programming Basics
A window may further contain more windows inside it. For example, take a calculator: the calculator window contains more windows in the form of buttons, radio buttons and check boxes. Every window has a parent and zero or more siblings, and a top-level window has the desktop as its parent.
-
Write the characteristics of child windows.
Topic: Windows Programming Basics
1. A child window always appears within the client area of its parent window. 2. Child windows are most often used as controls. 3. A child window sends WM_COMMAND notification messages to its parent window. 4. When a child window is created, a unique identifier for that window is specified in the hMenu parameter of CreateWindow().
-
Explain briefly how an application can perform more than one task at a time in the Windows environment.
Topic: Windows Programming Basics
Windows is a multitasking operating system. An application can perform more than one task at a time by using multiple processes, or more commonly by creating multiple threads within a single process. Each thread executes independently and the operating system's scheduler rapidly switches the CPU between threads, so the tasks appear to run simultaneously. For example, a word processor can check spelling in a worker thread while the user-interface thread continues to respond to typing. The user-interface thread owns the windows and message queue, while worker threads perform background tasks.
-
Explain system-defined messages. Why does an application need these messages?
Topic: Windows Programming Basics
System-defined messages are the standard messages (with names beginning with WM_) that the Windows operating system itself defines and sends to windows to notify them of events and to request actions — for example WM_PAINT (repaint the client area), WM_SIZE (window resized), WM_CLOSE, WM_DESTROY, WM_KEYDOWN and WM_COMMAND. An application needs these messages because all communication between the system and the application takes place through them: the system informs the application about user input and changes in the window's state, and the application's window procedure responds to each message appropriately. Without them the application could not interact with the user or the system.
-
Define the clipboard. How does it work?
Topic: Windows Programming Basics
The clipboard is a temporary storage area managed by User32.dll. It is used for cut, copy and paste operations: data is placed on the clipboard by one application and can then be pasted into the same or another application, so data becomes shareable among applications (for example, copying text from Notepad into MS Word). The data saved in the clipboard is lost when Windows is shut down.
-
Write down the steps involved in registering a window class, mentioning the function names involved in each step.
Topic: Window Classes and Messages
1. Declare and fill a WNDCLASS structure: set the class style (e.g. CS_HREDRAW | CS_VREDRAW), the window procedure address (lpfnWndProc), the instance handle (hInstance), the icon (hIcon), the cursor (hCursor), the background brush (hbrBackground), the menu name (lpszMenuName) and the class name (lpszClassName). 2. Call the RegisterClass() function, passing the address of the filled WNDCLASS structure. RegisterClass returns an ATOM that uniquely identifies the registered class (0 if registration fails).
-
Write down the steps involved in creating a window of a particular class (already registered) and dispatching messages from the application message queue to the window.
Topic: Window Classes and Messages
1. Create the window by calling CreateWindow(), giving the registered class name, window title, style, position, size, parent handle, menu handle, instance handle and creation data. CreateWindow returns the window handle (HWND). 2. Display the window with ShowWindow(hwnd, nCmdShow) and paint its client area with UpdateWindow(hwnd). 3. Run the message loop: repeatedly call GetMessage() to retrieve a message from the application message queue, TranslateMessage() to translate virtual-key messages into character messages, and DispatchMessage() to send the message to the window procedure of the destination window. The loop ends when GetMessage retrieves WM_QUIT.
-
Write the syntax of the CreateWindow function and tell about the parameters used in it.
Topic: Window Classes and Messages
HWND CreateWindow( LPCTSTR lpClassName, // class name (identification) LPCTSTR lpWindowName, // window caption (title bar) name DWORD dwStyle, // style of the window int x, // starting X position of the window on screen int y, // starting Y position of the window on screen int nWidth, // width of the window int nHeight, // height of the window HWND hWndParent, // handle of the parent window, if any HMENU hMenu, // handle of the menu, if any HINSTANCE hInstance, // handle of the application instance LPVOID lpParam // pointer to window-creation data );
-
How can we select a specific message from the message queue? Write the syntax of the function used.
Topic: Window Classes and Messages
A specific message (or a range of messages) can be selected from the queue by using the filter parameters of the GetMessage function: BOOL GetMessage( LPMSG lpMsg, // address of the MSG structure that receives the message HWND hWnd, // handle of the window whose messages are to be retrieved UINT wMsgFilterMin, // first message in the range to be retrieved UINT wMsgFilterMax // last message in the range to be retrieved ); If both filter values are 0 (or WM_KEYFIRST to WM_KEYLAST etc. as required), only messages in the given range are removed from the queue and returned.
-
Write the syntax of the SendMessage function, and also write what happens when the SendMessage function is used.
Topic: Window Classes and Messages
LRESULT SendMessage( HWND hWnd, // handle of the destination window UINT Msg, // message to be sent WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); An application typically sends a message to notify a window procedure to perform a task immediately. The SendMessage function sends the message directly to the window procedure corresponding to the given window, bypassing the message queue. The function waits until the window procedure completes the processing and then returns the message result. Parent and child windows often communicate by sending messages to each other.
-
What is the use of SendMessage() and PostMessage() functions? Also give the difference between them.
Topic: Window Classes and Messages
SendMessage(): The SendMessage function sends a message to the window procedure corresponding to the given window. The function waits until the window procedure completes processing and then returns the message result. PostMessage(): An application typically posts a message to notify a specific window to perform a task. PostMessage creates an MSG structure for the message and copies the message to the message queue; the application's message loop eventually retrieves the message and dispatches it to the appropriate window procedure. Difference: SendMessage delivers the message immediately and does not return until the message has been processed (synchronous), whereas PostMessage places the message in the queue and returns immediately, without waiting for processing (asynchronous).
-
Briefly define the modal loop.
Topic: Window Classes and Messages
A modal loop is run by modal dialog boxes and processes messages in the same way as the application message loop. When a modal dialog box is displayed, program execution is transferred to the modal loop, so the modal loop itself gets the messages from the queue and dispatches them; the owner window remains inactive until the dialog box is destroyed.
-
When is a message queue created?
Topic: Window Classes and Messages
A message queue is created when any GDI function call is made, or when SendMessage or PostMessage function calls are made. A message queue can be attached to every thread, whether it is a user-interface thread or a worker thread. User-interface threads always have a message queue.
-
Define a virtual-key message. How is the character value of a key retrieved from it?
Topic: Window Classes and Messages
A virtual-key message contains a virtual-key code — a device-independent value defined by the system that identifies which key was pressed — but not its character value. To retrieve the character value, the message loop must contain TranslateMessage, which translates the virtual-key message into a character message (WM_CHAR) and places it back into the application message queue.
-
Separate the system window classes that can be used by user processes from the system window classes that are used only by the system. (Button, DDEMLEvent, Message, ScrollBar, ComboLBox)
Topic: Window Classes and Messages
Used by user processes: Button, ScrollBar. Used only by the system: DDEMLEvent, Message, ComboLBox.
-
How do we translate a GetLastError() code into a string?
Topic: Window Classes and Messages • 5 marks marks
Call GetLastError() immediately after the failing API call to get the extended error code, and then pass that code to the FormatMessage function, which formats the corresponding system error message string: DWORD err = GetLastError(); char buffer[256]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, buffer, 256, NULL); // buffer now contains the error description string FormatMessage with the FORMAT_MESSAGE_FROM_SYSTEM flag looks up the message text for the error code in the system's message table and copies it into the supplied buffer.
-
Differentiate between pen and brush.
Topic: GDI and Painting
Pen: A pen is a graphics tool that a Windows application uses to draw lines and curves. Pens are used to draw freehand lines, straight lines and curves, to designate trends in graphs, and to outline bar graphs and pie charts. Brush: A brush is a graphics tool that a Windows-based application uses to paint the interior of polygons, ellipses and paths. Brushes are used to paint shapes, and to paint the sections of pie charts and the bars in bar graphs.
-
Write at least two responsibilities of GDI.
Topic: GDI and Painting
GDI (Graphics Device Interface) is a subsystem responsible for displaying text and images on display devices and printers. It acts as a buffer between applications and output devices, and it provides device-independent graphics functions, so the same drawing code works on different display and printing devices.
-
Name the two working spaces in the GDI environment.
Topic: GDI and Painting
In the GDI environment there are two working spaces: 1. Logical space 2. Physical space
-
An application can set up for itself any logical coordinate system using an API. Write down any two mapping modes.
Topic: GDI and Painting
Using the SetMapMode function an application can select any of these mapping modes (any two): 1. MM_TEXT — each logical unit is mapped to one device pixel; positive x is to the right and positive y is down. 2. MM_LOMETRIC — each logical unit is mapped to 0.1 mm. 3. MM_HIMETRIC — each logical unit is mapped to 0.01 mm. 4. MM_ISOTROPIC — logical units are mapped to device units with equally scaled axes. 5. MM_ANISOTROPIC — logical units are mapped to device units with arbitrarily scaled axes.
-
List down the pre-defined GDI objects in Windows.
Topic: GDI and Painting
Pre-defined (stock) GDI objects in Windows are: - Pens - Brushes - Fonts - Palettes - Bitmaps
-
Define the structure of PAINTSTRUCT.
Topic: GDI and Painting
The PAINTSTRUCT structure contains information for an application; this information can be used to paint the client area of a window owned by that application. typedef struct tagPAINTSTRUCT { HDC hdc; // handle to the device context BOOL fErase; // erase background, if this parameter is true RECT rcPaint; // rectangle of the invalid (update) region BOOL fRestore; BOOL fIncUpdate; // updation true/false BYTE rgbReserved[32]; // reserved; used internally by the system } PAINTSTRUCT, *PPAINTSTRUCT;
-
Write at least two tasks performed by the BeginPaint() function.
Topic: GDI and Painting
1. The BeginPaint() function prepares the specified window for painting and fills a PAINTSTRUCT structure with information about the painting. 2. BeginPaint() first erases the background of the window's client area by sending the WM_ERASEBKGND message. 3. If the function succeeds, the return value is the handle to a display device context for the specified window.
-
What will happen if GetUpdateRect returns zero?
Topic: GDI and Painting
An application calls the GetUpdateRect function to determine whether the window has an update region. If GetUpdateRect returns zero, the application should not call the BeginPaint and EndPaint functions.
-
Write three conditions in which the WM_PAINT message is sent.
Topic: GDI and Painting
1. Any hidden part of the window becomes visible. 2. The window is resized (and the CS_VREDRAW / CS_HREDRAW style bits were set while registering the window class). 3. The program scrolls its window. 4. InvalidateRect or InvalidateRgn is called by the application.
-
It is sometimes more efficient for an application to draw directly in a window without relying on the WM_PAINT message. How can this task be accomplished?
Topic: GDI and Painting
This can be useful when the user needs immediate feedback, such as when selecting text or dragging/sizing an object; in such cases the application usually draws while processing keyboard or mouse messages. To draw in a window without using a WM_PAINT message, the application uses the GetDC or GetDCEx function to retrieve a display device context for the window. With the display device context, the application can draw in the window. When the application has finished drawing, it calls the ReleaseDC function to release the device context for use by other applications. If the application draws a selection and an intervening WM_PAINT message occurs, the application must ensure that the drawing done during the message does not corrupt the selection; to avoid this, many applications remove the selection, carry out the usual drawing operations, and then restore the selection when drawing is complete.
-
Explain briefly how we can invoke the WM_PAINT message when no region of the window has become invalid.
Topic: GDI and Painting
WM_PAINT is generated when a part of the window becomes invalid, but it can also be invoked artificially by invalidating a region ourselves. The application calls InvalidateRect(hwnd, &rect, TRUE) — or InvalidateRect(hwnd, NULL, TRUE) to invalidate the entire client area — or InvalidateRgn, which adds the specified rectangle to the window's update region. The system then generates a WM_PAINT message so that the window procedure repaints the area. (RedrawWindow with the RDW_INVALIDATE flag achieves the same result.)
-
What happens if an application does not process the WM_ERASEBKGND message but passes it to DefWindowProc?
Topic: GDI and Painting
If the application does not process WM_ERASEBKGND and passes it to DefWindowProc, the default window procedure erases the background using the class background brush (the hbrBackground member of the WNDCLASS structure). If an application does process WM_ERASEBKGND, it should use the message's wParam parameter, which contains a handle to the display device context for the window, to draw the background, and then return a nonzero value. This ensures that BeginPaint does not erroneously set the fErase member of the PAINTSTRUCT structure to a nonzero value (indicating the background should be erased) when the application processes the subsequent WM_PAINT message.
-
What are the types of brushes? Briefly explain.
Topic: GDI and Painting
There are two types of brushes: logical and physical. A logical brush is one that you define in code as the ideal combination of color and/or pattern that an application should use to paint shapes. A physical brush is one that a device driver creates, based on your logical-brush definition.
-
How does an application get a handle to a stock object?
Topic: GDI and Painting
An application calls the GetStockObject function to get a handle to a stock object, and the returned handle is then used as a standard object handle, e.g.: hPen = GetStockObject(BLACK_PEN);
-
Sometimes, before selecting a new GDI object into a device context, we keep the previously selected object stored. Why?
Topic: GDI and Painting
The common practice is to track the original object that was selected into the DC and select it back when all the work with the new object is accomplished. A stock or created object should not be deleted while it is still selected into a device context, so the original object is restored first; only then can the new object be safely deleted.
-
Define the realization process.
Topic: GDI and Painting
Objects are converted from logical objects to physical objects using the realization process. Selecting a logical object into a DC involves converting the logical object into a physical object that the device driver uses for output. This process is called realization.
-
Write down the complete syntax of the GetDC function.
Topic: GDI and Painting
HDC GetDC( HWND hWnd // handle to the window ); The GetDC function retrieves a handle to a display device context (DC) for the client area of a specified window. If hWnd is NULL, GetDC retrieves the DC for the entire screen. The system retrieves the device context from the cache whenever an application calls GetDC or BeginPaint, and returns the DC to the cache when the application subsequently calls ReleaseDC or EndPaint.
-
Write the complete syntax of the GetParent function. What kind of value does it return, and when is this function used?
Topic: Dialogs, Controls and Subclassing
HWND GetParent( HWND hWnd // handle to the child window ); The GetParent function returns the handle of the parent window of the specified child window. This function is useful when the parent of a child window is to be used, for example to send a message to the parent or to get its properties.
-
Differentiate between super classing and sub classing.
Topic: Dialogs, Controls and Subclassing
Super classing: Super-classing defines a class that adds new functionality to a predefined window class. It involves creating a new class that uses the window procedure of an existing class for basic functionality; the new class must be registered like any other window class. Sub classing: Subclassing replaces the window procedure of an existing window (or class) with a new procedure within the same process. Subclassing is allowed only within a process — an application cannot subclass a window or class that belongs to another process, because Win32 processes have separate address spaces.
-
When an application subclasses a window, in which three manners can it respond when it gets a message?
Topic: Dialogs, Controls and Subclassing • 3 marks marks
When an application subclasses a window, it can take three actions with the message: 1. Pass the message to the original window procedure. 2. Modify the message and pass it to the original window procedure. 3. Not pass the message (handle it completely itself).
-
Name two common controls in Windows programming.
Topic: Dialogs, Controls and Subclassing
Common controls include: 1. Date Time Picker control 2. List View control (Other examples: Tree View, List Box, Combo Box, Progress Bar, ToolBar and Status Bar.)
-
Write a program using the WinMain function in which you will display a message box. The message box should display "Just Hello World Program!"
Topic: Program Writing • 5 marks marks
#include <windows.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // call the MessageBox API with NULL as the parent window handle MessageBox(NULL, "Just Hello World Program!", "Hello World", MB_OK | MB_ICONEXCLAMATION); return 0; }
-
Write down the WinMain function of an application that creates a window of a pre-registered (system) window class.
Topic: Program Writing • 10 marks marks
System window classes (such as BUTTON, EDIT, STATIC) are already registered by the system, so no RegisterClass call is needed; the window is created directly with CreateWindow: #include <windows.h> int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { HWND hwnd; MSG msg; // create a window of the pre-registered system class "BUTTON" hwnd = CreateWindow("BUTTON", "Click Me", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 300, 200, NULL, NULL, hInstance, NULL); if (hwnd == NULL) return 0; ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; }
-
Write the WinMain and window class registration code of an application that creates a simple overlapped window with a white background.
Topic: Program Writing • 10 marks marks
#include <windows.h> LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASS wc; HWND hwnd; MSG msg; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH); // white background wc.lpszMenuName = NULL; wc.lpszClassName = "MyWindowClass"; if (!RegisterClass(&wc)) return 0; hwnd = CreateWindow("MyWindowClass", "Simple Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 400, 300, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wParam, lParam); }
-
Make a program that registers a window class named "Test Window Class" with these features: the window redraws if its size changes; dark gray background using DKGRAY_BRUSH; default application icon; vertical two-headed arrow cursor using IDC_SIZENS. The handle of the current instance should be assigned to the appropriate structure variable and the remaining variables set to NULL or zero. If registration fails, display a message box with the message "Test Window class can not be registered", an OK button and the title "Error". Then create a main window named "First Test Window" of this class: an overlapped window with horizontal and vertical scroll bars, default position, width 340 and height 180, and a disabled close button. If creation fails, display a message box "First Test Window, can not be created" with an OK button and the title "Error". Also implement the message loop, which retrieves all messages from the message queue, translates them into character form and dispatches them one by one.
Topic: Program Writing • 20 marks marks
#include <windows.h> LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASS wc; HWND hwnd; MSG msg; HMENU hMenu; wc.style = CS_HREDRAW | CS_VREDRAW; // redraw if size changes wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; // current instance handle wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); // default icon wc.hCursor = LoadCursor(NULL, IDC_SIZENS); // two-headed arrow wc.hbrBackground = (HBRUSH) GetStockObject(DKGRAY_BRUSH); // dark gray wc.lpszMenuName = NULL; wc.lpszClassName = "Test Window Class"; if (!RegisterClass(&wc)) { MessageBox(NULL, "Test Window class can not be registered", "Error", MB_OK); return 0; } hwnd = CreateWindow("Test Window Class", "First Test Window", WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL, CW_USEDEFAULT, CW_USEDEFAULT, 340, 180, NULL, NULL, hInstance, NULL); if (hwnd == NULL) { MessageBox(NULL, "First Test Window, can not be created", "Error", MB_OK); return 0; } // disable the close button on the system menu hMenu = GetSystemMenu(hwnd, FALSE); EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED); ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); // message loop: retrieve, translate and dispatch messages one by one while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd, message, wParam, lParam); }
-
Write a window procedure function that explicitly handles the window closing functionality by pressing any key. This functionality can be achieved by handling the WM_CHAR message. You can use the DestroyWindow function for closing the window. Also provide appropriate functionality against WM_DESTROY and the default message.
Topic: Program Writing
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CHAR: // a key is pressed DestroyWindow(hwnd); // close the window return 0; case WM_DESTROY: // window is being destroyed PostQuitMessage(0); return 0; default: // all other messages: default processing return DefWindowProc(hwnd, message, wParam, lParam); } }