'WinAPI'에 해당되는 글 26건

  1. 2009.01.17 WInAPI #27 메뉴
  2. 2009.01.14 WinAPI #26장 파일 입출력 (1)
  3. 2009.01.14 WinAPI #19 공통 컨트롤
2009.01.17 18:40

27장 메뉴

 

HMENU GetSubMenu(

HMENU hMenu,

int nPos

);

Parameters

 

hMenu

[in] Handle to the menu.

nPos

[in] Specifies the zero-based relative position in the specified menu of an item that activates a drop-down menu or submenu.

Return Value

 

If the function succeeds, the return value is a handle to the drop-down menu or submenu activated by the menu item. If the menu item does not activate a drop-down menu or submenu, the return value is NULL

 

BOOL TrackPopupMenu(

HMENU hMenu,

UINT uFlags,

int x,

int y,

int nReserved,

HWND hWnd,

HWND prcRect

);

 

Parameters

 

hMenu

[in] Handle to the shortcut menu to be displayed. The handle can be obtained by calling CreatePopupMenu to create a new shortcut menu, or by calling GetSubMenu to retrieve a handle to a submenu associated with an existing menu item.

uFlags

[in] Use zero of more of these flags to specify function options.

Use one of the following flags to specify how the function positions the shortcut menu horizontally.

TPM_CENTERALIGN

If this flag is set, the function centers the shortcut menu horizontally relative to the coordinate specified by the x parameter.

TPM_LEFTALIGN

If this flag is set, the function positions the shortcut menu so that its left side is aligned with the coordinate specified by the x parameter.

TPM_RIGHTALIGN

Positions the shortcut menu so that its right side is aligned with the coordinate specified by the x parameter.

Use one of the following flags to specify how the function positions the shortcut menu vertically.

TPM_BOTTOMALIGN

If this flag is set, the function positions the shortcut menu so that its bottom side is aligned with the coordinate specified by the y parameter.

TPM_TOPALIGN

If this flag is set, the function positions the shortcut menu so that its top side is aligned with the coordinate specified by the y parameter.

TPM_VCENTERALIGN

If this flag is set, the function centers the shortcut menu vertically relative to the coordinate specified by the y parameter.

Use the following flags to determine the user selection without having to set up a parent window for the menu.

TPM_NONOTIFY

If this flag is set, the function does not send notification messages when the user clicks on a menu item.

TPM_RETURNCMD

If this flag is set, the function returns the menu item identifier of the user's selection in the return value.

Use one of the following flags to specify which mouse button the shortcut menu tracks.

TPM_LEFTBUTTON

If this flag is set, the user can select menu items with only the left mouse button.

TPM_RIGHTBUTTON

If this flag is set, the user can select menu items with both the left and right mouse buttons.

Windows 98/Me, Windows 2000/XP:Use any reasonable combination of the following flags to modify the animation of a menu. For example, by selecting a horizontal and a vertical flag you can achieve diagonal animation.

TPM_HORNEGANIMATION

Animates the menu from right to left.

TPM_HORPOSANIMATION

Animates the menu from left to right.

TPM_NOANIMATION

Displays menu without animation.

TPM_VERNEGANIMATION

Animates the menu from bottom to top.

TPM_VERPOSANIMATION

Animates the menu from top to bottom.

For any animation to occur, the SystemParametersInfo function must set SPI_SETMENUANIMATION. Also, all the TPM_*ANIMATION flags, except TPM_NOANIMATION, are ignored if menu fade animation is on, See the SPI_GETMENUFADE flag in SystemParametersInfo.

 

Windows 98/Me, Windows 2000/XP: Use the TPM_RECURSE flag to display a menu when another menu is already displayed. This is intended to support context menus within a menu.

 

Windows XP: To have text layout from right-to-left, use TPM_LAYOUTRTL. By default, the text layout is left-to-right.

x

[in] Specifies the horizontal location of the shortcut menu, in screen coordinates.

y

[in] Specifies the vertical location of the shortcut menu, in screen coordinates.

nReserved

Reserved; must be zero.

hWnd

[in] Handle to the window that owns the shortcut menu. This window receives all messages from the menu. The window does not receive a WM_COMMAND message from the menu until the function returns. If you specify TPM_NONOTIFY in the uFlags parameter, the function does not send messages to the window identified by hWnd. However, you must still pass a window handle in hWnd. It can be any window handle from your application.

prcRect

Ignored.

 

Return Value

If you specify TPM_RETURNCMD in the uFlags parameter, the return value is the menu-item identifier of the item that the user selected. If the user cancels the menu without making a selection, or if an error occurs, then the return value is zero.

 

If you do not specify TPM_RETURNCMD in the uFlags parameter, the return value is nonzero if the function succeeds and zero if it fails. To get extended error information, call GetLastError.

DWORD CheckMenuItem(

HMENU hmenu,

UINT uIDCheckItem,

UINT uCheck

);

 

Parameters

 

hmenu

[in] Handle to the menu of interest.

uIDCheckItem

[in] Specifies the menu item whose check-mark attribute is to be set, as determined by the uCheck parameter.

uCheck

[in] Specifies flags that control the interpretation of the uIDCheckItem parameter and the state of the menu item's check-mark attribute. This parameter can be a combination of either MF_BYCOMMAND, or MF_BYPOSITION and MF_CHECKED or MF_UNCHECKED.

MF_BYCOMMAND

Indicates that the uIDCheckItem parameter gives the identifier of the menu item. The MF_BYCOMMAND flag is the default, if neither the MF_BYCOMMAND nor MF_BYPOSITION flag is specified.

MF_BYPOSITION

Indicates that the uIDCheckItem parameter gives the zero-based relative position of the menu item.

MF_CHECKED

Sets the check-mark attribute to the selected state.

MF_UNCHECKED

Sets the check-mark attribute to the clear state.

 

BOOL EnableMenuItem(

HMENU hMenu,

UINT uIDEnableItem,

UINT uEnable

);

사용 금지하려면 MF_GRAYED 플래그를 지정하며 사용을 허가하려면 MF_ENABLED 플래그를 지정.

 

UINT GetMenuState(

HMENU hMenu,

UINT uId,

UINT uFlags

);

 

BOOL CheckMenuRadioItem(

HMENU hmenu,

UINT idFirst,

UINT idLast,

UINT idCheck,

UINT uFlags

);

 

 

BOOL SetMenuItemBitmaps(

HMENU hMenu,

UINT uPosition,

UINT uFlags,

HBITMAP hBitmapUnchecked,

HBITMAP hBitmapChecked

);

체크 비트맵 변경함수

 

BOOL ModifyMenu( HMENU hMnu,

UINT uPosition,

UINT uFlags,

PTR uIDNewItem,

LPCTSTR lpNewItem

);

캡션의 변경.

 

BOOL AppendMenu(

HMENU hMenu,

UINT uFlags,

UINT_PTR uIDNewItem,

LPCTSTR lpNewItem

);

 

BOOL DeleteMenu(

HMENU hMenu,

UINT uPosition,

UINT uFlags

);

BOOL InsertMenu(

HMENU hMenu,

UINT uPosition,

UINT uFlags,

PTR uIDNewItem,

LPCTSTR lpNewItem

);

 

BOOL InsertMenuItem(

HMENU hMenu,

UINT uItem,

BOOL fByPosition,

LPCMENUITEMINFO lpmii

);

 

HMENU GetSystemMenu(

HWND hWnd,

BOOL bRevert

);

bRevert는 이 함수의 동작을 지정. FALSE이면 시스템 메뉴의 복사본을 만든 후 그 핸들을 리턴. 시스템 메뉴를 원하는대로 변경하면 됨. TRUE이면 시스템 메뉴를 원래대로 리셋시키며 변경된 시스템 메뉴는 파괴. 메뉴의 추가 삭제도 가능.

 

HMENU LoadMenu(

HINSTANCE hInstance,

LPCTSTR lpMenuName

);

 

BOOL SetMenu(

HWND hWnd,

HMENU hMenu

);

LoadMenu로 리소스에서 메뉴 템플릿을 읽어온 후 SetMenu로 윈도우에 붙임.

 

HMENU CreateMenu(VOID);

HMENU CreatePopupMenu(VOID);

실행중에 메뉴를 만듬. AppendMenu로 추가

 

비트맵 메뉴

생략~

'WinAPI' 카테고리의 다른 글

WInAPI #27 메뉴  (0) 2009.01.17
WinAPI #26장 파일 입출력  (1) 2009.01.14
WinAPI #19 공통 컨트롤  (0) 2009.01.14
WinAPI #18 스크롤 바  (0) 2009.01.14
WinAPI #17 에디트  (0) 2009.01.13
WinAPI #16 리스트 박스  (0) 2009.01.13
Posted by hyunny82
TAG WINAPI

26장 파일 입출력

 

파일에서 데이터 읽을 때

BOOL ReadFile(

HANDLE hFile,

LPVOID lpBuffer,

DWORD nNumberOfBytesToRead,

LPDWORD lpNumberOfBytesRead,

LPOVERLAPPED lpOverlapped

);

 

파일을 다 읽은 후 파일 핸들을 닫는다.

BOOL CloseHandle(

HANDLE hObject

);

 

파일을 여는 함수

HANDLE CreateFile(

LPCTSTR lpFileName,

DWORD dwDesiredAccess,

DWORD dwShareMode,

LPSECURITY_ATTRIBUTES lpSecurityAttributes,

DWORD dwCreationDisposition,

DWORD dwFlagsAndAttributes,

HANDLE hTemplateFile

);

 

lpFileName

[in] A pointer to a null-terminated string that specifies the name of an object to create or open.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.

 

To create a file stream, specify the name of the file, a colon, and then the name of the stream. For more information, see File Streams.

 

Windows Me/98/95: This string must not exceed MAX_PATH characters.

dwDesiredAccess

[in] The access to the object, which can be read, write, or both.

For more information, see File Security and Access Rights. You cannot request an access mode that conflicts with the sharing mode that is specified in an open request that has an open handle.

 

If this parameter is 0 (zero), the application can query file and device attributes without accessing a device. This is useful for an application to determine the size of a floppy disk drive and the formats it supports without requiring a floppy in a drive. It can also be used to test for the existence of a file or directory without opening them for read or write access.

 

dwShareMode

[in] The sharing mode of an object, which can be read, write, both, or none.

You cannot request a sharing mode that conflicts with the access mode that is specified in an open request that has an open handle, because that would result in the following sharing violation: ERROR_SHARING_VIOLATION). For more information, see Creating and Opening Files.

 

If this parameter is 0 (zero) and CreateFile succeeds, the object cannot be shared and cannot be opened again until the handle is closed. For more information, see the Remarks section of this topic.

 

The sharing options remain in effect until you close the handle to an object.

 

To enable a processes to share an object while another process has the object open, use a combination of one or more of the following values to specify the access mode they can request to open the object.

 

Value Meaning

FILE_SHARE_DELETE Enables subsequent open operations on an object to request delete access.

Otherwise, other processes cannot open the object if they request delete access.

 

If this flag is not specified, but the object has been opened for delete access, the function fails.

 

Windows Me/98/95: This flag is not supported.

FILE_SHARE_READ Enables subsequent open operations on an object to request read access.

Otherwise, other processes cannot open the object if they request read access.

 

If this flag is not specified, but the object has been opened for read access, the function fails.

FILE_SHARE_WRITE Enables subsequent open operations on an object to request write access.

Otherwise, other processes cannot open the object if they request write access.

 

If this flag is not specified, but the object has been opened for write access, the function fails.

 

lpSecurityAttributes

[in] A pointer to a SECURITY_ATTRIBUTES structure that determines whether or not the returned handle can be inherited by child processes.

If lpSecurityAttributes is NULL, the handle cannot be inherited.

 

The lpSecurityDescriptor member of the structure specifies a security descriptor for an object. If lpSecurityAttributes is NULL, the object gets a default security descriptor. The access control lists (ACL) in the default security descriptor for a file or directory are inherited from its parent directory.

 

The target file system must support security on files and directories for this parameter to have an effect on them, which is indicated when GetVolumeInformation returns FS_PERSISTENT_ACLS.

 

CreateFile ignores lpSecurityDescriptor when opening an existing file, but continues to use the other structure members.

 

dwCreationDisposition

[in] An action to take on files that exist and do not exist.

For more information, see the Remarks section of this topic.

 

This parameter must be one of the following values. Value Meaning

CREATE_ALWAYS Creates a new file, always.

If a file exists, the function overwrites the file, clears the existing attributes, combines the specified file attributes, and flags with FILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor that the SECURITY_ATTRIBUTES structure specifies.

CREATE_NEW Creates a new file.

The function fails if a specified file exists.

OPEN_ALWAYS Opens a file, always.

If a file does not exist, the function creates a file as if dwCreationDisposition is CREATE_NEW.

OPEN_EXISTING Opens a file.

The function fails if the file does not exist.

 

For more information, see the Remarks section of this topic.

TRUNCATE_EXISTING Opens a file and truncates it so that its size is 0 (zero) bytes.

The function fails if the file does not exist.

 

The calling process must open the file with the GENERIC_WRITE access right.

 

dwFlagsAndAttributes

[in] The file attributes and flags.

This parameter can include any combination of the file attributes. All other file attributes override FILE_ATTRIBUTE_NORMAL.

 

When CreateFile opens a file, it combines the file flags with existing file attributes, and ignores any supplied file attributes.

 

The following file attributes and flags are used only for file objects, not other types of objects that CreateFile creates.

 

Attribute Meaning

FILE_ATTRIBUTE_ARCHIVE A file should be archived. Applications use this attribute to mark files for backup or removal.

FILE_ATTRIBUTE_ENCRYPTED A file or directory is encrypted. For a file, this means that all data in the file is encrypted. For a directory, this means that encryption is the default for newly created files and subdirectories. For more information, see File Encryption.

This flag has no effect if FILE_ATTRIBUTE_SYSTEM is also specified.

FILE_ATTRIBUTE_HIDDEN A file is hidden. Do not include it in an ordinary directory listing.

FILE_ATTRIBUTE_NORMAL A file does not have other attributes set. This attribute is valid only if used alone.

FILE_ATTRIBUTE_NOT_CONTENT_INDEXED A file is not indexed by the content indexing service.

FILE_ATTRIBUTE_OFFLINE The data of a file is not immediately available. This attribute indicates that file data is physically moved to offline storage. This attribute is used by Remote Storage, the hierarchical storage management software. Applications should not arbitrarily change this attribute.

FILE_ATTRIBUTE_READONLY A file is read only. Applications can read the file, but cannot write to or delete it.

FILE_ATTRIBUTE_SYSTEM A file is part of or used exclusively by an operating system.

FILE_ATTRIBUTE_TEMPORARY A file is being used for temporary storage. File systems avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.

 

 

This parameter can also include any combination of the following flags.

 

 

Flag Meaning

FILE_FLAG_BACKUP_SEMANTICS A file is being opened or created for a backup or restore operation. The system ensures that the calling process overrides file security checks when the process has SE_BACKUP_NAME and SE_RESTORE_NAME privileges. For more information, see Changing Privileges in a Token.

You can set this flag to obtain a handle to a directory. A directory handle can be passed to some functions instead of a file handle. For more information, see Obtaining A Handle to a Directory.

 

Windows Me/98/95: This flag is not supported.

FILE_FLAG_DELETE_ON_CLOSE The system deletes a file immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles.

If there are existing open handles to a file, the call fails unless they were all opened with the FILE_SHARE_DELETE share mode.

 

Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified.

FILE_FLAG_NO_BUFFERING The system opens a file with no system caching. This flag does not affect hard disk caching. When combined with FILE_FLAG_OVERLAPPED, the flag gives maximum asynchronous performance, because the I/O does not rely on the synchronous operations of the memory manager. However, some I/O operations take more time, because data is not being held in the cache. Also, the file metadata may still be cached. To flush the metadata to disk, use the FlushFileBuffers function.

An application must meet certain requirements when working with files that are opened with FILE_FLAG_NO_BUFFERING:

 

 

File access must begin at byte offsets within a file that are integer multiples of the volume sector size.

File access must be for numbers of bytes that are integer multiples of the volume sector size. For example, if the sector size is 512 bytes, an application can request reads and writes of 512, 1024, or 2048 bytes, but not of 335, 981, or 7171 bytes.

Buffer addresses for read and write operations should be sector aligned, which means aligned on addresses in memory that are integer multiples of the volume sector size. Depending on the disk, this requirement may not be enforced.

One way to align buffers on integer multiples of the volume sector size is to use VirtualAlloc to allocate the buffers. It allocates memory that is aligned on addresses that are integer multiples of the operating system's memory page size. Because both memory page and volume sector sizes are powers of 2, this memory is also aligned on addresses that are integer multiples of a volume sector size.

 

An application can determine a volume sector size by calling the GetDiskFreeSpace function.

FILE_FLAG_OPEN_NO_RECALL The file data is requested, but it should continue to be located in remote storage. It should not be transported back to local storage. This flag is for use by remote storage systems.

FILE_FLAG_OPEN_REPARSE_POINT The system inhibits the reparse behavior of NTFS file system reparse points. When a file is opened, a file handle is returned, whether or not the filter that controls the reparse point is operational. This flag cannot be used with the CREATE_ALWAYS flag.

FILE_FLAG_OVERLAPPED The file is being opened or created for asynchronous I/O. When the operation is complete, the event specified to the call in the OVERLAPPED structure is set to the signaled state. Operations that take a significant amount of time to process return ERROR_IO_PENDING.

If this flag is specified, the file can be used for simultaneous read and write operations. The system does not maintain the file pointer, therefore you must pass the file position to the read and write functions in the OVERLAPPED structure or update the file pointer.

 

If this flag is not specified, then I/O operations are serialized, even if the calls to the read and write functions specify an OVERLAPPED structure.

FILE_FLAG_POSIX_SEMANTICS A file is accessed according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support that naming. Use care when using this option, because files created with this flag may not be accessible by applications that are written for MS-DOS or 16-bit Windows.

FILE_FLAG_RANDOM_ACCESS A file is accessed randomly. The system can use this as a hint to optimize file caching.

FILE_FLAG_SEQUENTIAL_SCAN A file is accessed sequentially from beginning to end. The system can use this as a hint to optimize file caching. If an application moves the file pointer for random access, optimum caching may not occur. However, correct operation is still guaranteed.

Specifying this flag can increase performance for applications that read large files using sequential access. Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges of bytes.

FILE_FLAG_WRITE_THROUGH The system writes through any intermediate cache and goes directly to disk.

If FILE_FLAG_NO_BUFFERING is not also specified, so that system caching is in effect, then the data is written to the system cache, but is flushed to disk without delay.

 

If FILE_FLAG_NO_BUFFERING is also specified, so that system caching is not in effect, then the data is immediately flushed to disk without going through the system cache. The operating system also requests a write-through the hard disk cache to persistent media. However, not all hardware supports this write-through capability.

 

 

If the CreateFile function opens the client side of a named pipe, the dwFlagsAndAttributes parameter can also contain Security Quality of Service information. For more information, see Impersonation Levels. When the calling application specifies the SECURITY_SQOS_PRESENT flag, the dwFlagsAndAttributes parameter can contain one or more of the following values.

 

 

Value Meaning

SECURITY_ANONYMOUS Impersonates a client at the Anonymous impersonation level.

SECURITY_CONTEXT_TRACKING The security tracking mode is dynamic. If this flag is not specified, the security tracking mode is static.

SECURITY_DELEGATION Impersonates a client at the Delegation impersonation level.

SECURITY_EFFECTIVE_ONLY Only the enabled aspects of the client's security context are available to the server. If you do not specify this flag, all aspects of the client's security context are available.

This allows the client to limit the groups and privileges that a server can use while impersonating the client.

SECURITY_IDENTIFICATION Impersonates a client at the Identification impersonation level.

SECURITY_IMPERSONATION Impersonate a client at the impersonation level.

 

hTemplateFile

[in] A handle to a template file with the GENERIC_READ access right. The template file supplies file attributes and extended attributes for the file that is being created. This parameter can be NULL.

When opening an existing file, CreateFile ignores the template file.

 

Windows Me/98/95: The hTemplateFile parameter must be NULL. If you supply a handle, the call fails and GetLastError returns ERROR_NOT_SUPPORTED.

Return Values

If the function succeeds, the return value is an open handle to a specified file. If a specified file exists before the function call and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS, even when the function succeeds. If a file does not exist before the call, GetLastError returns 0 (zero).

 

If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

 

Remarks

Use the CloseHandle function to close an object handle that CreateFile returns.

 

Windows Server 2003 and Windows XP/2000: A sharing violation occurs if an attempt is made to open a file or directory for deletion on a remote computer when the value of the dwDesiredAccess parameter is the DELETE access flag OR'ed with any other access flag, and the remote file or directory has not been opened with FILE_SHARE_DELETE. To avoid the sharing violation in this scenario, open the remote file or directory with the DELETE access right only, or call DeleteFile without first opening the file or directory for deletion.

Some file systems, such as the NTFS file system, support compression or encryption for individual files and directories. On volumes that are formatted for that kind of file system, a new file inherits the compression and encryption attributes of its directory.

 

You cannot use CreateFile to control compression on a file or directory. For more information, see File Compression and Decompression, and File Encryption.

 

 

Windows Server 2003 and Windows XP/2000: For backward compatibility purposes, CreateFile does not apply inheritance rules when you specify a security descriptor in lpSecurityAttributes. To support inheritance, functions that later query the security descriptor of this object may heuristically determine and report that inheritance is in effect. For more information, see Automatic Propagation of Inheritable ACEs.

Windows Me/98/95: CreateFileW is supported by the Microsoft Layer for Unicode. To use this, you must add specific files to your application, which are identified in Microsoft Layer for Unicode on Windows 95/98/Me Systems.

Files

 

If you try to create a file on a floppy drive that does not have a floppy disk or a CD-ROM drive that does not have a CD, the system displays a message for the user to insert a disk or a CD. To prevent the system from displaying this message, call the SetErrorMode function with SEM_FAILCRITICALERRORS.

 

Windows Server 2003 and Windows XP/2000: If CREATE_ALWAYS and FILE_ATTRIBUTE_NORMAL are specified, CreateFile fails and sets the last error to ERROR_ACCESS_DENIED if the file exists and has the FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM attribute. To avoid the error, specify the same attributes as the existing file.

For more information, see Creating and Opening Files.

 

If you rename or delete a file and then restore it shortly afterward, the system searches the cache for file information to restore. Cached information includes its short/long name pair and creation time.

 

Windows Me/98/95: This remark does not apply.

 

If you call CreateFile on a file that is pending deletion as a result of a previous call to DeleteFile, the function fails. The operating system delays file deletion until all handles to the file are closed. GetLastError returns ERROR_ACCESS_DENIED.

 

When an application creates a file across a network, it is better to use GENERIC_READ | GENERIC_WRITE than to use GENERIC_WRITE alone. The resulting code is faster, because the redirector can use the cache manager and send fewer SMBs with more data. This combination also avoids an issue where writing to a file across a network can occasionally return ERROR_ACCESS_DENIED.

 

 

File Streams

 

On NTFS file systems, you can use CreateFile to create separate streams within a file. For more information, see File Streams.

 

 

Directories

 

An application cannot create a directory by using CreateFile. The application must call CreateDirectory or CreateDirectoryEx to create a directory. To opening a directory by using CreateFile, use the FILE_FLAG_BACKUP_SEMANTICS flag.

 

When using CreateFile to open a directory during defragmentation of a FAT or FAT32 file system volume, do not specify the MAXIMUM_ALLOWED access right. Access to the directory is denied if this is done. Specify the GENERIC_READ access right instead.

 

 

Physical Disks and Volumes

 

You can use the CreateFile function to open a physical disk drive or a volume. The function returns a handle that can be used with the DeviceIoControl function. This enables you to access the disk partition table. However, it is potentially dangerous to do so, because an incorrect write to a disk could make its contents inaccessible. The following requirements must be met for such a call to succeed:

 

 

The caller must have administrative privileges. For more information, see Running with Special Privileges.

The dwCreationDisposition parameter must have the OPEN_EXISTING flag.

When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITE flag.

When opening a physical drive x, the lpFileName string should be the following form: \\.\PHYSICALDRIVE<x>. Hard disk numbers start at 0 (zero). The following table shows some examples of physical drive strings.

 

String Meaning

\\.\PHYSICALDRIVE0 Opens the first physical drive.

\\.\PHYSICALDRIVE2 Opens the third physical drive.

 

For an example of opening a physical drive, see Calling DeviceIoControl.

 

When opening a volume or floppy drive, the lpFileName string should be the following form: \\.\<x>:. Do not use a trailing backslash, which indicates the root directory of a drive. The following table shows some examples of drive strings.

 

String Meaning

\\.\A: Opens drive A (floppy drive).

\\.\C: Opens drive C (volume).

 

You can also open a volume by referring to its volume name. For more information, see Naming a Volume.

 

Volume handles can be opened as noncached at the discretion of the file system, even when the noncached option is not specified in CreateFile. You should assume that all Microsoft file systems open volume handles as noncached. The restrictions on noncached I/O for files also apply to volumes.

 

A file system may or may not require buffer alignment even though the data is noncached. However, if the noncached option is specified when opening a volume, buffer alignment is enforced regardless of the file system on the volume. It is recommended on all file systems that you open volume handles as noncached, and follow the noncached I/O restrictions.

 

 

Tape Drives

 

You can open tape drives by using a file name of the following form: \\.\TAPEx where x is a number that indicates which drive to open, starting with tape drive 0 (zero). To open tape drive 0 (zero) in an application that is written in C or C++, use the following file name: "\\\\.\\TAPE0". For more information, see Backup.

 

Windows Me/98/95: Opening tape drives is not supported.

 

Communications Resources

 

The CreateFile function can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, and the template parameter must be NULL. Read, write, or read/write access can be specified, and the handle can be opened for overlapped I/O. For more information about communications, see Communications.

 

 

Consoles

 

The CreateFile function can create a handle to console input (COIN$). If the process has an open handle to it as a result of inheritance or duplication, it can also create a handle to the active screen buffer (COPOUT$). The calling process must be attached to an inherited console or one allocated by the Alloc console function. For console handles, set the CreateFile parameters as follows.

 

Parameters Value

lpFileName Use the COIN$ value to specify console input.

 

Use the COPOUT$ value to specify console output.

 

COIN$ gets a handle to the console input buffer, even if the SetStdHandle function redirects the standard input handle. To get the standard input handle, use the GetStdHandle function.

 

COPOUT$ gets a handle to the active screen buffer, even if SetStdHandle redirects the standard output handle. To get the standard output handle, use GetStdHandle.

dwDesiredAccess GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access.

dwShareMode When opening COIN$, specify FILE_SHARE_READ. When opening COPOUT$, specify FILE_SHARE_WRITE.

 

If the calling process inherits the console, or if a child process should be able to access the console, this parameter must be FILE_SHARE_READ | FILE_SHARE_WRITE.

lpSecurityAttributes If you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE.

dwCreationDisposition You should specify OPEN_EXISTING when using CreateFile to open the console.

dwFlagsAndAttributes Ignored.

hTemplateFile Ignored.

 

The following table shows various settings of dwDesiredAccess and lpFileName.

 

lpFileName dwDesiredAccess Result

CON GENERIC_READ Opens console for input.

CON GENERIC_WRITE Opens console for output.

CON GENERIC_READ GENERIC_WRITE Causes CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND.

Windows Me/98/95: Causes CreateFile to fail; GetLastError returns ERROR_PATH_NOT_FOUND.

 

 

Mailslots

 

If CreateFile opens the client end of a mailslot, the function returns INVALID_HANDLE_VALUE if the mailslot client attempts to open a local mailslot before the mailslot server has created it with the CreateMailSlot function. For more information, see Mailslots.

 

 

Pipes

 

If CreateFile opens the client end of a named pipe, the function uses any instance of the named pipe that is in the listening state. The opening process can duplicate the handle as many times as required, but after it is opened, the named pipe instance cannot be opened by another client. The access that is specified when a pipe is opened must be compatible with the access that is specified in the dwOpenMode parameter of the CreateNamedPipe function. For more information, see Pipes.

 

 

Example Code

For an example, see Creating and Opening Files.

 

Requirements

Client Requires Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.

Server Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server.

Header Declared in Winbase.h; include Windows.h.

Library Link to Kernel32.lib.

DLL Requires Kernel32.dll.

Unicode Implemented as CreateFileW (Unicode) and CreateFileA (ANSI). Note that Unicode support on Windows Me/98/95 requires Microsoft Layer for Unicode.

파일 쓰기

BOOL WriteFile(

HANDLE hFile,

LPCVOID lpBuffer,

DWORD nNumberOfBytesToWrite,

LPDWORD lpNumberOfBytesWritten,

LPOVERLAPPED lpOverlapped

);

 

임의 접근

DWORD SetFilePointer(

HANDLE hFile,

LONG lDistanceToMove,

PLONG lpDistanceToMoveHigh,

DWORD dwMoveMethod

);

 

FILE_BEGIN The starting point is 0 (zero) or the beginning of the file.

FILE_CURRENT The starting point is the current value of the file pointer.

FILE_END The starting point is the current end-of-file position.

 

비동기 입출력

CreateFile 함수로 파일 열 때 FILE_FLAG_OVERLAPPED 플래그를 지정. ReadFile, WriteFile 함수의 마지막 인수에 OVERLAPPED 구조체의 포인터를 전달.

 

 

 

typedef struct _OVERLAPPED {

ULONG_PTR Internal;

ULONG_PTR InternalHigh;

union {

struct {

DWORD Offset;

DWORD OffsetHigh;

};

PVOID Pointer;

};

HANDLE hEvent;

} OVERLAPPED, *LPOVERLAPPED;

 

응용 프로그램의 입출력 진행 상태 확인.

BOOL GetOverlappedResult(

HANDLE hFile,

LPOVERLAPPED lpOverlapped,

LPDWORD lpNumberOfBytesTransferred,

BOOL bWait

);

파일 복사

case WM_LBUTTONDOWN:

SetCursor(LoadCursor(NULL,IDC_WAIT));

CopyFile(TEXT("c:\\BigFile.txt"),TEXT("c:\\BigFile.bak"),FALSE);

MessageBox(hWnd,TEXT("백업 파일을 복사했습니다"),TEXT("알람"),MB_OK);

SetCursor(LoadCursor(NULL,IDC_ARROW));

return 0;

 

BOOL CopyFileEx(

LPCTSTR lpExistingFileName,

LPCTSTR lpNewFileName,

LPPROGRESS_ROUTINE lpProgressRoutine,

LPVOID lpData,

LPBOOL pbCancel,

DWORD dwCopyFlags

);

lpProgressRoutine에 콜백함수를 주기적으로 호출하는 기능과 복사중에 중지할 수 있는 기능이 있다.

pbCancel에 TRUE 입력시 복사 중지.

 

파일 이동

BOOL MoveFile(

LPCTSTR lpExistingFileName,

LPCTSTR lpNewFileName

);

BOOL MoveFileEx(

LPCTSTR lpExistingFileName,

LPCTSTR lpNewFileName,

DWORD dwFlags

);

삭제

BOOL DeleteFile(

LPCTSTR lpFileName

);

 

int rename(const char* oldname, const char* newname);

디렉토리도 변경가능. C 런타임 함수.

 

DWORD GetFileSize(

HANDLE hFile,

LPDWORD lpFileSizeHigh

);

DWORD GetFileAttributes(

LPCTSTR lpFileName

);

 

int _access(const char* path, int mode);

path에 대상 파일을 주고 mode에 조사하고자 하는 엑세스 타입을 준다. 요청한 타입이 맞으면 0 아니면 -1 리턴. 사용시 io.h 인클루드 해야 함. Full Path 입력

 

int SHFileOperation(LPSHFILEOPSTRUCT lpFileOp);

복사. 이동, 삭제, 이름 변경등 하나의 함수로 처리. 쉘이 제공 탐색기가 파일을 관리할 때 이 함수를 사용.

 

typedef struct _SHFILEOPSTRUCT {

HWND hwnd;

UINT wFunc;

LPCTSTR pFrom;

LPCTSTR pTo;

FILEOP_FLAGS fFlags;

BOOL fAnyOperationsAborted;

LPVOID hNameMappings;

LPCTSTR lpszProgressTitle;

} SHFILEOPSTRUCT, *LPSHFILEOPSTRUCT;

caseWM_LBUTTONDOWN:

fo.hwnd=hWnd;

fo.wFunc=FO_COPY;

fo.pFrom=TEXT("c:\\Util");

fo.pTo=TEXT("c:\\Temp\\Util");

fo.fFlags=0;

SHFileOperation(&fo);

return0;

 

 

 

 

 

 

'WinAPI' 카테고리의 다른 글

WInAPI #27 메뉴  (0) 2009.01.17
WinAPI #26장 파일 입출력  (1) 2009.01.14
WinAPI #19 공통 컨트롤  (0) 2009.01.14
WinAPI #18 스크롤 바  (0) 2009.01.14
WinAPI #17 에디트  (0) 2009.01.13
WinAPI #16 리스트 박스  (0) 2009.01.13
Posted by hyunny82
TAG WINAPI

19장 공통 컨트롤

프로그래스

caseWM_CREATE:

InitCommonControls();

hProg=CreateWindow(PROGRESS_CLASS,NULL,WS_CHILD|WS_VISIBLE|WS_BORDER,10,10,400,30,hWnd,NULL,g_hInst,NULL);

 

스타일

PBS_SMOOTH

구획별로 나누어지지 않은 꽉 찬 그래프

PBS_VERTICAL

수직으로 값이 증가

메시지

PBM_SETRANGE

범위 설정. LOWORD(lParam)최소값 HIWORD(lParam)으로 최대값 지정 디폴트 0~100

PBM_SETPOS

wParam으로 위치를 설정

PBM_DELTAPOS

wParam이 지정하는 만큼 위치를 증감. 새위치는 현재위치 +wParam이 된다

PBM_SETSTEP

단계 증가값을 wParam으로 지정

PBM_STEPIT

단계 증가값만큼 위치를 증가

PBM_SETRANGE32

wParam으로 최소값, lParam으로 최대값 지정. 65535이상 범위를 가지는 프로그래스 만들 때 사용.

PBM_GETRANGE

현재 설정된 범위 얻음

PBM_GETPOS

현재 설정된 위치를 얻음

 

트랙바

caseWM_CREATE:

InitCommonControls();

hProg=CreateWindow(TRACKBAR_CLASS,NULL,WS_CHILD|WS_VISIBLE,10,100,300,40,hWnd,NULL,g_hInst,NULL);

 

p733참조

 

업다운

caseWM_CREATE:

InitCommonControls();

hProg=CreateWindow(UPDOWN_CLASS, NULL, WS_CHILD|WS_VISIBLE|UDS_SETBUDDYINT|UDS_ALIGNRIGHT, 0,0,0,0, hWnd, NULL, g_hInst, NULL);

hEdit=CreateWindow(TEXT("edit"),NULL, WS_CHILD|WS_VISIBLE|WS_BORDER ,10,10,100,30,hWnd,NULL, g_hInst, NULL);

SendMessage(hProg,UDM_SETBUDDY,(WPARAM)hEdit,0);

p736참조

HWND CreateUpDownControl(DWORD dwStyle, int x, int y, inc cx, int cy, HWND hParent, int nID, HINSTANCE hInst, HWND hBuddy, int nUpper, int nLower, int nPos);

 

애니메이트

 

툴팁

typedef struct tagTOOLINFO{

UINT cbSize;

UINT uFlags;

HWND hwnd;

UINT_PTR uId;

RECT rect;

HINSTANCE hinst;

LPTSTR lpszText;

#if (_WIN32_IE >= 0x0300)

LPARAM lParam;

#endif

} TOOLINFO, NEAR *PTOOLINFO, *LPTOOLINFO;

 

cbSize

버전 확인 구조체 sizeof(TOOLINFO) 대입.

uFlags

툴팁의 표시 방식 지정 플래그. 조합가능

TTF_ABSOLUTE

Version 4.70. Positions the ToolTip window at the same coordinates provided by TTM_TRACKPOSITION. This flag must be used with the TTF_TRACK flag.

TTF_CENTERTIP

Centers the ToolTip window below the tool specified by the uId member.

TTF_IDISHWND

Indicates that the uId member is the window handle to the tool. If this flag is not set, uId is the tool's identifier.

TTF_PARSELINKS

Version 6.00. Indicates that links in the tooltip text should be parsed.

Note that Comctl32.dll version 6 is not redistributable but it is included in Microsoft Windows XP or later. To use Comctl32.dll version 6, specify it in a manifest. For more information on manifests, see Using Windows XP Visual Styles.

 

TTF_RTLREADING

Indicates that the ToolTip text will be displayed in the opposite direction to the text in the parent window.

TTF_SUBCLASS

Indicates that the ToolTip control should subclass the tool's window to intercept messages, such as WM_MOUSEMOVE. If this flag is not set, you must use the TTM_RELAYEVENT message to forward messages to the ToolTip control. For a list of messages that a ToolTip control processes, see TTM_RELAYEVENT.

TTF_TRACK

Version 4.70. Positions the ToolTip window next to the tool to which it corresponds and moves the window according to coordinates supplied by the TTM_TRACKPOSITION messages. You must activate this type of tool using the TTM_TRACKACTIVATE message.

TTF_TRANSPARENT

Version 4.70. Causes the ToolTip control to forward mouse event messages to the parent window. This is limited to mouse events that occur within the bounds of the ToolTip window.

 

hwnd

툴의 부모 윈도우 핸들

 

uId

툴의 고유 번호에 해당하는 ID. TTF_IDISHWND 플래그가 있으면 이 값은 툴의 윈도우 핸들이 되며 사각영역. TTF_IDISHWND 플래그가 없으면 이 값은 0부터 시작되는 툴의 일련 번호.

 

rect

툴의 사각영역을 지정. 윈도우 툴인 경우 핸들로부터 영역을 구할 수 있으므로 이 멤버는 무시.

 

hinst

문자열 리소스를 가진 인스턴스 핸들. 문자열 리소스 쓰지 않을 경우 무시.

 

lpszText

툴 텍스트 문자열. 세가지 형태로 지정. LPSTR_TEXTCALLBACK 값을 주면 부모 윈도우에게

TTN_GETDISPINFR 통지 메시지를 보내 실행중에 문자열 구함. 툴 텍스트 구할 때 이 멤버는 충분한 길이의 버퍼를 가리키고 있어야 한다.

 

lParam

사용자 정의 데이터.

 

멤버

윈도우 툴

사각영역 툴

uFlags

TTF_IDISHWND 포함

TTF_IDISHWND 미포함

hId

툴의 윈도우 핸들

0부터 시작 툴 고유 번호

rect

무시

사각영역 좌표

 

case WM_CREATE:

iccex.dwICC=ICC_WIN95_CLASSES;

iccex.dwSize=sizeof(INITCOMMONCONTROLSEX);

InitCommonControlsEx(&iccex);

 

hTip=CreateWindowEx(WS_EX_TOPMOST,TOOLTIPS_CLASS,NULL,0,

CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,

hWnd,NULL,g_hInst,NULL);

 

hBtn=CreateWindow(TEXT("button"),TEXT("버튼"),WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,50,50,200,100,hWnd,(HMENU)0,g_hInst,NULL);

 

ti.cbSize=sizeof(TOOLINFO);

ti.uFlags=TTF_SUBCLASS | TTF_IDISHWND;

ti.hwnd=hWnd;

ti.uId=(WPARAM)hBtn;

ti.lpszText=TEXT("버튼입니다");

SendMessage(hTip,TTM_ADDTOOL,0,(LPARAM)(LPTOOLINFO)&ti);

 

ti.uFlags=TTF_SUBCLASS;

ti.hwnd=hWnd;

ti.uId=0;

ti.lpszText=TEXT("사각영역입니다");

ti.rect=rt;

SendMessage(hTip,TTM_ADDTOOL,0,(LPARAM)(LPTOOLINFO)&ti);

return 0;

색상

TTM_SETTIPBKCOLOR, TTM_SETTIPTEXTCOLOR 메시지 사용 wParam으로 변경 색상값 전달.

 

여백

TTM_SETMARGIN 메시지로 간격 조정 lParam으로 각 변의 간격을 지정하는 RECT 구조체를 전달. 조사할 때는 TTM_GETMARGIN 메시지를 사용하되 lParam으로 RECT 구조체의 포인터를 전달.

 

최대폭

최대폭조사나 설정 TTM_G(S)ETMAXTIPWIDTH 메시지를 사용. lParam으로 최대폭의 픽셀값을 전달.

 

폰트 변경

WM_SETFONT 메시지의 wParam으로 전달. 조사는 WM_GETFONT메시지를 사용. 이 사용 후 반드시 파괴.

풍선형 도움말

스타일 TTF_BALLOON.

툴 텍스트를 변경.

TTM_UPDATETIPTEXT 메시지 사용.

 

트래킹 툴팁

TTF_TRACK 프로그램이 출력 위치나 시점 결정. TTF_ABSOLUTE 주면 TTM_TRACKPOSITION 메시지로 지정한 위치에 정확하게 출력. TTM_UPDATETIPTEXT 와 함께 사용하면 하나의 툴팁으로 출력 시점, 위치, 툴 텍스트까지 프로그래밍.

 

 

 

'WinAPI' 카테고리의 다른 글

WInAPI #27 메뉴  (0) 2009.01.17
WinAPI #26장 파일 입출력  (1) 2009.01.14
WinAPI #19 공통 컨트롤  (0) 2009.01.14
WinAPI #18 스크롤 바  (0) 2009.01.14
WinAPI #17 에디트  (0) 2009.01.13
WinAPI #16 리스트 박스  (0) 2009.01.13
Posted by hyunny82

티스토리 툴바