티스토리 툴바

블로그 이미지
pminp

calendar

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        

Notice

Recent Comment

Recent Trackback

Archive

2011/07/17 00:11 유익한 사이트
크리에이티브 커먼즈 라이선스
Creative Commons License
http://vsts2010.net/
저작자 표시 비영리 변경 금지
posted by pminp
2009/12/28 17:48 win32
크리에이티브 커먼즈 라이선스
Creative Commons License

What is a DLL?

A DLL is a library that contains code and data that can be used by more than one program at the same time. For example, in Windows operating systems, the Comdlg32 DLL performs common dialog box related functions. Therefore, each program can use the functionality that is contained in this DLL to implement an Open dialog box. This helps promote code reuse and efficient memory usage.

By using a DLL, a program can be modularized into separate components. For example, an accounting program may be sold by module. Each module can be loaded into the main program at run time if that module is installed. Because the modules are separate, the load time of the program is faster, and a module is only loaded when that functionality is requested.

Additionally, updates are easier to apply to each module without affecting other parts of the program. For example, you may have a payroll program, and the tax rates change each year. When these changes are isolated to a DLL, you can apply an update without needing to build or install the whole program again.

The following list describes some of the files that are implemented as DLLs in Windows operating systems:
  • ActiveX Controls (.ocx) files
    An example of an ActiveX control is a calendar control that lets you select a date from a calendar.
  • Control Panel (.cpl) files
    An example of a .cpl file is an item that is located in Control Panel. Each item is a specialized DLL.
  • Device driver (.drv) files
    An example of a device driver is a printer driver that controls the printing to a printer.

DLL advantages

The following list describes some of the advantages that are provided when a program uses a DLL:
  • Uses fewer resources
    When multiple programs use the same library of functions, a DLL can reduce the duplication of code that is loaded on the disk and in physical memory. This can greatly influence the performance of not just the program that is running in the foreground, but also other programs that are running on the Windows operating system.
  • Promotes modular architecture
    A DLL helps promote developing modular programs. This helps you develop large programs that require multiple language versions or a program that requires modular architecture. An example of a modular program is an accounting program that has many modules that can be dynamically loaded at run time.
  • Eases deployment and installation
    When a function within a DLL needs an update or a fix, the deployment and installation of the DLL does not require the program to be relinked with the DLL. Additionally, if multiple programs use the same DLL, the multiple programs will all benefit from the update or the fix. This issue may more frequently occur when you use a third-party DLL that is regularly updated or fixed.

DLL dependencies

When a program or a DLL uses a DLL function in another DLL, a dependency is created. Therefore, the program is no longer self-contained, and the program may experience problems if the dependency is broken. For example, the program may not run if one of the following actions occurs:
  • A dependent DLL is upgraded to a new version.
  • A dependent DLL is fixed.
  • A dependent DLL is overwritten with an earlier version.
  • A dependent DLL is removed from the computer.
These actions are generally known as DLL conflicts. If backward compatibility is not enforced, the program may not successfully run.

The following list describes the changes that have been introduced in Microsoft Windows 2000 and in later Windows operating systems to help minimize dependency issues:
  • Windows File Protection
    In Windows File Protection, the operating system prevents system DLLs from being updated or deleted by an unauthorized agent. Therefore, when a program installation tries to remove or update a DLL that is defined as a system DLL, Windows File Protection will look for a valid digital signature.
  • Private DLLs
    Private DLLs let you isolate a program from changes that are made to shared DLLs. Private DLLs use version-specific information or an empty .local file to enforce the version of the DLL that is used by the program. To use private DLLs, locate your DLLs in the program root folder. Then, for new programs, add version-specific information to the DLL. For old programs, use an empty .local file. Each method tells the operating system to use the private DLLs that are located in the program root folder.

DLL troubleshooting tools

Several tools are available to help you troubleshoot DLL problems. The following tools are some of these tools.

Dependency Walker

The Dependency Walker tool can recursively scan for all dependent DLLs that are used by a program. When you open a program in Dependency Walker, Dependency Walker performs the following checks:
  • Dependency Walker checks for missing DLLs.
  • Dependency Walker checks for program files or DLLs that are not valid.
  • Dependency Walker checks that import functions and export functions match.
  • Dependency Walker checks for circular dependency errors.
  • Dependency Walker checks for modules that are not valid because the modules are for a different operating system.
By using Dependency Walker, you can document all the DLLs that a program uses. This may help prevent and correct DLL problems that may occur in the future. Dependency Walker is located in the following directory when you install Microsoft Visual Studio 6.0:
drive\Program Files\Microsoft Visual Studio\Common\Tools

DLL Universal Problem Solver

The DLL Universal Problem Solver (DUPS) tool is used to audit, compare, document, and display DLL information. The following list describes the utilities that make up the DUPS tool:
  • Dlister.exe
    This utility enumerates all the DLLs on the computer and logs the information to a text file or to a database file.
  • Dcomp.exe
    This utility compares the DLLs that are listed in two text files and produces a third text file that contains the differences.
  • Dtxt2DB.exe
    This utility loads the text files that are created by using the Dlister.exe utility and the Dcomp.exe utility into the dllHell database.
  • DlgDtxt2DB.exe
    This utility provides a graphical user interface (GUI) version of the Dtxt2DB.exe utility.
For more information about the DUPS tool, click the following article number to view the article in the Microsoft Knowledge Base:
247957  (http://support.microsoft.com/kb/247957/ ) Using DUPS.exe to resolve DLL compatibility problems

DLL Help database

The DLL Help database helps you locate specific versions of DLLs that are installed by Microsoft software products. For more information about the DLL Help database, visit the following Microsoft Web site:
http://support.microsoft.com/dllhelp/?FR=1 (http://support.microsoft.com/dllhelp/)

DLL development

This section describes the issues and the requirements that you should consider when you develop your own DLLs.

Types of DLLs

When you load a DLL in an application, two methods of linking let you call the exported DLL functions. The two methods of linking are load-time dynamic linking and run-time dynamic linking.
Load-time dynamic linking
In load-time dynamic linking, an application makes explicit calls to exported DLL functions like local functions. To use load-time dynamic linking, provide a header (.h) file and an import library (.lib) file when you compile and link the application. When you do this, the linker will provide the system with the information that is required to load the DLL and resolve the exported DLL function locations at load time.
Run-time dynamic linking
In run-time dynamic linking, an application calls either the LoadLibrary function or the LoadLibraryEx function to load the DLL at run time. After the DLL is successfully loaded, you use the GetProcAddress function to obtain the address of the exported DLL function that you want to call. When you use run-time dynamic linking, you do not need an import library file.

The following list describes the application criteria for when to use load-time dynamic linking and when to use run-time dynamic linking:
  • Startup performance
    If the initial startup performance of the application is important, you should use run-time dynamic linking.
  • Ease of use
    In load-time dynamic linking, the exported DLL functions are like local functions. This makes it easy for you to call these functions.
  • Application logic
    In run-time dynamic linking, an application can branch to load different modules as required. This is important when you develop multiple-language versions.

The DLL entry point

When you create a DLL, you can optionally specify an entry point function. The entry point function is called when processes or threads attach themselves to the DLL or detached themselves from the DLL. You can use the entry point function to initialize data structures or to destroy data structures as required by the DLL. Additionally, if the application is multithreaded, you can use thread local storage (TLS) to allocate memory that is private to each thread in the entry point function. The following code is an example of the DLL entry point function.
BOOL APIENTRY DllMain(
HANDLE hModule,	// Handle to DLL module
	DWORD ul_reason_for_call,	// Reason for calling function
	LPVOID lpReserved ) // Reserved
{
	switch ( ul_reason_for_call )
	{
		case DLL_PROCESS_ATTACHED:
		// A process is loading the DLL.
		break;
		case DLL_THREAD_ATTACHED:
		// A process is creating a new thread.
		break;
		case DLL_THREAD_DETACH:
		// A thread exits normally.
		break;
		case DLL_PROCESS_DETACH:
		// A process unloads the DLL.
		break;
	}
	return TRUE;
}
When the entry point function returns a FALSE value, the application will not start if you are using load-time dynamic linking. If you are using run-time dynamic linking, only the individual DLL will not load.

The entry point function should only perform simple initialization tasks and should not call any other DLL loading or termination functions. For example, in the entry point function, you should not directly or indirectly call the LoadLibrary function or the LoadLibraryEx function. Additionally, you should not call the FreeLibrary function when the process is terminating.

Note In multithreaded applications, make sure that access to the DLL global data is synchronized (thread safe) to avoid possible data corruption. To do this, use TLS to provide unique data for each thread.

Exporting DLL functions

To export DLL functions, you can either add a function keyword to the exported DLL functions or create a module definition (.def) file that lists the exported DLL functions.

To use a function keyword, you must declare each function that you want to export with the following keyword:
__declspec(dllexport)
To use exported DLL functions in the application, you must declare each function that you want to import with the following keyword:
__declspec(dllimport)
Typically, you would use one header file that has a define statement and an ifdef statement to separate the export statement and the import statement.

You can also use a module definition file to declare exported DLL functions. When you use a module definition file, you do not have to add the function keyword to the exported DLL functions. In the module definition file, you declare the LIBRARY statement and the EXPORTS statement for the DLL. The following code is an example of a definition file.
// SampleDLL.def
//
LIBRARY "sampleDLL"

EXPORTS
  HelloWorld

Sample DLL and application

In Microsoft Visual C++ 6.0, you can create a DLL by selecting either the Win32 Dynamic-Link Library project type or the MFC AppWizard (dll) project type.

The following code is an example of a DLL that was created in Visual C++ by using the Win32 Dynamic-Link Library project type.
// SampleDLL.cpp
//

#include "stdafx.h"
#define EXPORTING_DLL
#include "sampleDLL.h"

BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
    return TRUE;
}

void HelloWorld()
{
	MessageBox( NULL, TEXT("Hello World"), TEXT("In a DLL"), MB_OK);
}
// File: SampleDLL.h
//
#ifndef INDLL_H
#define INDLL_H

#ifdef EXPORTING_DLL
extern __declspec(dllexport) void HelloWorld() ;
#else
extern __declspec(dllimport) void HelloWorld() ;
#endif

#endif
The following code is an example of a Win32 Application project that calls the exported DLL function in the SampleDLL DLL.
// SampleApp.cpp 
//

#include "stdafx.h"
#include "sampleDLL.h"

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{ 	
	HelloWorld();
	return 0;
}
Note In load-time dynamic linking, you must link the SampleDLL.lib import library that is created when you build the SampleDLL project.

In run-time dynamic linking, you use code that is similar to the following code to call the SampleDLL.dll exported DLL function.
...
typedef VOID (*DLLPROC) (LPTSTR);
...
HINSTANCE hinstDLL;
DLLPROC HelloWorld;
BOOL fFreeDLL;

hinstDLL = LoadLibrary("sampleDLL.dll");
if (hinstDLL != NULL)
{
    HelloWorld = (DLLPROC) GetProcAddress(hinstDLL, "HelloWorld");
    if (HelloWorld != NULL)
        (HelloWorld);

    fFreeDLL = FreeLibrary(hinstDLL);
}
...
When you compile and link the SampleDLL application, the Windows operating system searches for the SampleDLL DLL in the following locations in this order:
  1. The application folder
  2. The current folder
  3. The Windows system folder

    Note The GetSystemDirectory function returns the path of the Windows system folder.
  4. The Windows folder

    Note The GetWindowsDirectory function returns the path of the Windows folder.
posted by pminp
2009/09/28 18:25 win32
크리에이티브 커먼즈 라이선스
Creative Commons License

GDI Technical Articles

Flicker-Free Displays Using an Off-Screen DC

 

Herman Rodent
Microsoft Developer Network Technology Group

Created: April 5, 1993

 

Abstract

This article describes a technique for drawing to a window device context (DC) in such a way that the screen does not flicker. The technique is very simple and easy to implement.

Introduction

I often see Microsoft® Windows™-based applications that maintain status information such as the current time in a small control window that flickers very annoyingly each time it's updated. All the standard Windows controls flicker if updated at frequent intervals. The solution to this problem is to implement a simple control yourself and use an off-screen DC to construct the image, which is then copied in total to the client area of the control window. The net result is a control that can be updated without any flicker.

Flicker, the sample application included with this article, has window procedures for two controls—one of these flickers; the other one doesn't. The application creates an instance of each of these controls and updates the window text ten times every second to show how one flickers and the other doesn't. The controls both support the system text color, window background color, and the WM_SETTEXT and WM_SETFONT messages.

A Control That Flickers

Let's start by looking at the window procedure of the control class that flickers. After that, we can go on to see how this is changed to prevent flickering. Here's the window procedure for the control:

LRESULT CALLBACK FlickerWndProc(HWND hWnd, UINT msg,
                                WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
 
    switch(msg) {
    case WM_SETTEXT:
        lstrcpy(szCaption, (LPSTR)lParam);
        InvalidateRect(hWnd, NULL, TRUE);
        break;
 
    case WM_SETFONT:
        hfnt = (HFONT) wParam;
        break;
 
    case WM_PAINT:
        BeginPaint(hWnd, &ps);
        Paint(hWnd, &ps);
        EndPaint(hWnd, &ps);
        break;
 
    default:
        return DefWindowProc(hWnd, msg, wParam, lParam);
        break;
    }
    return NULL;
}

The window supports WM_SETTEXT, WM_SETFONT, and WM_PAINT messages. When it receives a WM_SETTEXT message, the window copies the text to a local buffer and then invalidates the entire window to force the sending of a WM_PAINT message. When the window receives a WM_SETFONT message, it saves the font handle for use in its paint routine. Most of the work is done by the paint routine, which is shown here:

static void Paint(HWND hWnd, LPPAINTSTRUCT lpPS)
{
    RECT rc;
    HFONT hfntOld = NULL;
 
    GetClientRect(hWnd, &rc);
    SetBkMode(lpPS->hdc, TRANSPARENT);
 
    if (hfnt) {
        hfntOld = SelectObject(lpPS->hdc, hfnt);
    }
 
    SetTextColor(lpPS->hdc, GetSysColor(COLOR_WINDOWTEXT));
 
    DrawText(lpPS->hdc,
             szCaption,
             -1,
             &rc,
             DT_CENTER);
 
    if (hfntOld) {
        SelectObject(lpPS->hdc, hfntOld);
    }
}

At the start of the procedure, we get the client rectangle information that tells us where we can draw. The background mode is set to transparent, and if a WM_SETFONT message has provided a specific font handle, it is selected into the DC provided in the paint message. DrawText is then used to render the text into the DC and to restore the font, if it has been changed, to what it originally was.

What makes this window flicker when we update it frequently? The answer is that Windows asks the window procedure to repaint the window as a two-step process. First, it sends a WM_ERASEBKGND message and then a WM_PAINT message. The default handling for the WM_ERASEBKGND message is to fill the area with the current window background color. So the sequence of events is first to fill the area with solid color and then to draw the text on top. The net result of doing this frequently is that the window state alternates between its erased state and its drawn state—it flickers.

A Control That Doesn't Flicker

To prevent the control from flickering when we update it frequently, we need to make two changes to how the control handles messages. First, we need to prevent Windows from providing the default handling of WM_ERASEBKGND messages. Secondly, we need to handle WM_PAINT messages so that the background is painted with the window background color and so that the changes to the control's client area happen at once. Here's the new window procedure:

LRESULT CALLBACK NoFlickerWndProc(HWND hWnd, UINT msg,
                                  WPARAM wParam, LPARAM lParam)
{
    PAINTSTRUCT ps;
 
    switch(msg) {
    case WM_SETTEXT:
        lstrcpy(szCaption, (LPSTR)lParam);
        InvalidateRect(hWnd, NULL, TRUE);
        break;
 
    case WM_SETFONT:
        hfnt = (HFONT) wParam;
        break;
 
    case WM_ERASEBKGND:
        return (LRESULT)1; // Say we handled it.
 
    case WM_PAINT:
        BeginPaint(hWnd, &ps);
        Paint(hWnd, &ps);
        EndPaint(hWnd, &ps);
        break;
 
    default:
        return DefWindowProc(hWnd, msg, wParam, lParam);
        break;
    }
    return NULL;
}

The only change here is that we now process the WM_ERASEBKGND message by returning a nonzero value, which tells Windows that we have taken care of it. This prevents the DefWindowProc function from performing the default action, which would normally erase the client area. The other changes are made in the paint routine shown here:

static void Paint(HWND hWnd, LPPAINTSTRUCT lpPS)
{
    RECT rc;
    HDC hdcMem;
    HBITMAP hbmMem, hbmOld;
    HBRUSH hbrBkGnd;
    HFONT hfntOld;
 
    //
    // Get the size of the client rectangle.
    //
 
    GetClientRect(hWnd, &rc);
 
    //
    // Create a compatible DC.
    //
 
    hdcMem = CreateCompatibleDC(lpPS->hdc);
 
    //
    // Create a bitmap big enough for our client rectangle.
    //
 
    hbmMem = CreateCompatibleBitmap(lpPS->hdc,
                                    rc.right-rc.left,
                                    rc.bottom-rc.top);
 
    //
    // Select the bitmap into the off-screen DC.
    //
 
    hbmOld = SelectObject(hdcMem, hbmMem);
 
    //
    // Erase the background.
    //
 
    hbrBkGnd = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
    FillRect(hdcMem, &rc, hbrBkGnd);
    DeleteObject(hbrBkGnd);
 
    //
    // Select the font.
    //
 
    if (hfnt) {
        hfntOld = SelectObject(hdcMem, hfnt);
    }
 
    //
    // Render the image into the offscreen DC.
    //
 
    SetBkMode(hdcMem, TRANSPARENT);
    SetTextColor(hdcMem, GetSysColor(COLOR_WINDOWTEXT));
    DrawText(hdcMem,
             szCaption,
             -1,
             &rc,
             DT_CENTER);
 
    if (hfntOld) {
        SelectObject(hdcMem, hfntOld);
    }
 
    //
    // Blt the changes to the screen DC.
    //
 
    BitBlt(lpPS->hdc,
           rc.left, rc.top,
           rc.right-rc.left, rc.bottom-rc.top,
           hdcMem,
           0, 0,
           SRCCOPY);
 
    //
    // Done with off-screen bitmap and DC.
    //
 
    SelectObject(hdcMem, hbmOld);
    DeleteObject(hbmMem);
    DeleteDC(hdcMem);
 
}

As you can see, quite a lot has changed here. The new window procedure obtains the client rectangle coordinates as before and then creates a memory DC that is compatible with the DC supplied in the paint message. We can't draw to this DC with any effect yet because, by default, it has only a 1-by-1 monochrome bitmap associated with it. The next thing to do, therefore, is create a bitmap that has the same color organization as the DC we want to draw in and select that bitmap into the memory DC. Now we can draw on the memory DC, which will affect the bits in the bitmap selected in it. In other words, the bitmap will save the image of whatever we draw on the DC.

When the bitmap was created, nothing was done to any of the pixels in it, and consequently, we need to set them all to a known state. To do this, we fill the area with background color by creating a brush of that color and then using the FillRect function to do the work.

Once this has been done, we can perform the same operations that were performed in the flickering version: Set the background mode, select the font to use, and call DrawText to generate the text image. At this point the memory DC has the image of what we want to appear in the client area of the control window, and we can transfer the image from the memory DC to the window DC by calling BitBlt. This copies the entire rectangle (background and text image) in one go—and that's what stops you from seeing any flickering effect.

Once the blt is done, we can free the memory bitmap and DC, and exit the paint procedure.

Further Improvements

If performance is an issue for your application, you can do further optimizations.

Maintaining a Permanent Bitmap

Instead of creating a compatible bitmap each time the window is painted, you might consider creating the bitmap when the window is created and storing the handle to it in an extra word of window information created by setting the cbWndExtra field to sizeof(HBITMAP) when the window class is registered. At WM_CREATE time, allocate local memory for the bitmap and save the handle to it in the extra window word.

In processing the WM_PAINT message, you can quickly get the bitmap handle and proceed as before. This ensures that you cannot run out of local memory at paint time trying to allocate the bitmap, but does mean that you must also destroy and recreate the bitmap each time the window size changes.

Updating Only the Out-of-Date Regions

You may commonly find part of a large window area overlapped by another window, and consequently, much of what you might be painting is hidden. The PAINTSTRUCT information in the WM_PAINT message contains a clipping rectangle. You can use this information to work out what bits of your image need to be repainted and thus avoid repainting the entire thing needlessly. This is most effective when the paint procedure has a lot of work to do and least effective if the paint procedure has something simple like a blt to do.

Summary

Using an off-screen DC is simple to do and greatly enhances the visual impression of controls that have constantly changing data.

 

posted by pminp
TAG GDI, win32
prev 1 2 next