'MSDN'에 해당되는 글 15건

  1. 2010.04.27 warning C4995: 'xxx' : name was marked as #pragma deprecated
  2. 2009.07.16 GetLastError()
  3. 2009.05.28 다른 윈도우에서의 GetFocus() 사용하기
  4. 2008.10.01 노트북의 배터리 정보를 받아오자
  5. 2008.09.19 하드디스크 용량 가져오기
  6. 2008.09.04 DriverEntry()
  7. 2008.09.04 DEVICE_OBJECT
  8. 2008.09.04 DRIVER_OBJECT 1
  9. 2008.08.20 GetCurrentDirectory()를 이용한 Windows에서 현재경로 받아오기.. 1
  10. 2008.07.28 MSDN 키보드 입력 작동 방식 스크랩
2010. 4. 27. 14:30

warning C4995: 'xxx' : name was marked as #pragma deprecated



컴파일을 하다보면 "warning C4995: 'xxx': name was marked as #pragma deprecated" 와 같은 warning 메시지를 볼 때가 있다.

MSDN에 이렇게 나와있다.

Error Message

'function': name was marked as #pragma deprecated

The compiler encountered a function that was marked with pragma deprecated. The function may no longer be supported in a future release. You can turn this warning off with the warning pragma (example below).

더 이상  지원되지 않을 수 있는 함수이다.
warning을 보고 싶지 않으면 pargma를 사용해라.

#pragma warning(disable:4995)

위와 같은 처리를 하게 되면, 빌드 시에 warning 메시지는 나오지 않을 것이다.
하지만, 더 이상 지원이 되지 않는 함수라는 것은 뭔가 문제가 있기 때문에 그럴 것이다.

위의 경고를 내는 함수들은 버퍼 오버플로우 혹은 보안적으로 문제를 가질 수 있는 함수들이다. 그렇기 때문에 위의 경고 메시지를 낼 만한 함수의 사용을 자제하고, 개선 된 함수를 사용하는것이 방법이 될 것이다.

아래의 링크가 그 위의 문제를 해결하는데 도움을 줄 것이다.
http://msdn.microsoft.com/en-us/library/8ef0s5kh(VS.80).aspx
http://www.chaos3d.net/zboard/view.php?id=cs_public&no=17


2009. 7. 16. 10:00

GetLastError()



Windows 시스템에서 함수를 사용할 때 이녀석이 제대로 실행되지 않고 에러를 발생시킬 경우가 허다하다.
사실.. 프로그램을 짜면서 에러 하나 없이 순탄하게 짜는 사람이 있을까마는..
적어도 난 한번도 없다면서.. -_-;

그럼 에러가 발생했다 라는것 말고 무슨 이유로 에러가 발생했다는 것을 아는 방법이 없을까?
수정을 하려 해도 어떤 이유에서 에러가 발생하는 지 알아야 수정을 할것인데...
그래서 나온 것이 바로 GetLastError() 라는 함수이다. GetLastError()를 에러가 발생하는 함수 바로 뒤에 호출하게 되면 오류의 원인에 대한 에러코드를 얻을 수가 있다.

DWORD GetLastError(void);

MSDN을 보게 되면 수많은 에러코드의 의미가 나와있다.
오호라.. MSDN을 보니 대충 0 ~ 15999가지의 에러에 대한 내용이 있는 모양이다. 열라 많다 -_-;;

간단하게 사용법을 보면은..
...
HANDLE hFile = CreateFile(...);
if(hFile == INVALID_HANDLE_VALUE)
{
    printf("Error Code : %d \n", GetLastError());
}
...

위와 같이 사용을 하게 될 경우, CreateFile()의 결과가 잘못될 경우, if문의 GetLastError()의 반환값을 보구선 어떤 이유로 원치 않는 결과가 나왔는지를 확인 할 수가 있다.


'Programmings > Windows Programming' 카테고리의 다른 글

DLL에서 WndProc 메시지 처리하는 방법  (0) 2010.02.11
아스키코드(ASCII CODE)와 유티코드(UNICODE)  (0) 2009.10.09
WinIO  (0) 2009.06.23
IME 입력모드 설정  (5) 2009.05.29
레지스트리(Registry)  (0) 2009.05.29
2009. 5. 28. 16:02

다른 윈도우에서의 GetFocus() 사용하기



일반적으로 포커스를 가진 윈도우의 핸들을 가져오거나 지정하는데 사용되는 함수는 GetFocus(), SetFocus()이다. 하지만, 이들 함수들은 모든 윈도우의 포커스를 가져오는 것이 아니고, 현재 윈도우 내의 포커스를 가진 핸들을 가져오는 함수이다.

쉽게 말하자면, 자신의 윈도우에서 포커스를 가진 특정 윈도우(버튼, 에디트 박스 등)의 핸들을 가져올 때 사용하는 것은 문제가 없을 것이지만, 다른 윈도우를 대상으로 이 함수를 쓰게 된다면, 우리가 원하는 핸들 대신 NULL 값을 가져오게 될 것이다.
NULL 값을 가져온 경우 포커스를 가진 윈도우가 다른 스레드 메시지 큐에 있기 때문이다.

하지만, 이에 대한 해결 방법이 있다.
먼저 GetForegroundWindow() 를 사용하여 실제 포커스를 가진 윈도우의 최상위 부모 핸들을 얻는다. 그리고  이 윈도우의 스레드를 구해(GetWindowThreadProcessId()) 현재 스레드에 연결(AttachThreadInput())하면 된다. 이 후에 GetFocus()를 호출하게 되면, NULL 값이 아닌 포커스를 가진 다른 윈도우의 핸들을 가져오는 것을 확인 할 수 있다.

MDDN에서는 GetFocus에 대해 이렇게 설명하고 있다.

The GetFocus function retrieves the handle to the window that has the keyboard focus, if the window is attached to the calling thread's message queue.

Syntax

 HWND GetFocus(VOID);

Return Value

 The return value is the handle to the window with the keyboard focus. If the calling thread's message queue does not have an associated window with the keyboard focus, the return value is NULL.


Remarks

 GetFocus returns the window with the keyboard focus for the current thread's message queue. If GetFocus returns NULL, another thread's queue may be attached to a window that has the keyboard focus.

 Use the GetForegroundWindow function to retrieve the handle to the window with which the user is currently working. You can associate your thread's message queue with the windows owned by another thread by using the AttachThreadInput function.

 Windows 98/Me and Windows NT 4.0 SP3 and later:To get the window with the keyboard focus on the foreground queue or the queue of another thread, use the GetGUIThreadInfo function.


간단하게 예를 들어보면, 아래와 같은 방법으로 다른 윈도우의 포커스를 가져올 수 있다.
HWND hWnd = GetForegroundWindow();
DWORD fromId = GetCurrentThreadId();
DWORD toId = GetWindowThreadProcessId(hWnd, NULL);
AttachThreadInput(fromId, toId, TRUE);
HWND focus = GetFocus();

참고 웹사이트 ( http://ditongs.egloos.com/1353649 )

'Programmings > Windows Programming' 카테고리의 다른 글

IME 입력모드 설정  (5) 2009.05.29
레지스트리(Registry)  (0) 2009.05.29
서브클래싱  (0) 2009.05.26
GetWindowThreadProcessId()  (0) 2009.05.18
GetModuleFileNameEx()  (0) 2009.05.15
2008. 10. 1. 12:03

노트북의 배터리 정보를 받아오자


10월의 첫날부터... 이런 상투적인 업무 포스트밖에 올릴 것이 없다는게 참 슬프긴 하지만.. 그리도.. 머.. -_-;;

노트북의 배터리의 정보를 받아오는 부분에 대해서 뭔가를 하고 있다. 배터리의 용량, Voltage, 상태... 뭐 그밖의 등등..  검색을 하던중.. 좋은 정보를 얻어 포스팅 한다.
MSDN에서 검색을 했는데 'Enumerating Battery Devices'라고 꽤 쓸만한 예제 소스가 있었다.
여기(http://msdn.microsoft.com/en-us/library/bb204769(VS.85).aspx )를 클릭하면 정보를 얻을 수 있다.

이녀석을 바로 적용하면 동작하지는 않고 몇가지 수정을 해주어야 한다.
VS2005환경에서 Win32 API를 이용하여 테스트 프로그램을 작성하였다.

일단 필요한 헤더 파일('BatClass.h', 'Setupapi.h')을 적당한 위치에 넣어(#include)준다.
BatClass.h는 배터리에 관련된 것들을 정의해 놓은 헤더파일이고, Setupapi.h는 'SetupDiGetClassDevs', 'SetupDiEnumDeviceInterfaces', .. 등과 같은 함수들을 정의해 놓은 헤더파일이다.

헤더파일을 추가하고 컴파일을 하게 되면 에러가 뜰것이다. 안뜰지도 모르지만.. 본인의 경우에는 에러가 있었다.
HDEVINFO hdev = SetupDiGetClassDevs(&GUID_DEVCLASS_BATTERY, 0, 0, DIGCF_PRESENT |                                                                DIGCF_DEVICEINTERFACE);
위의 위치에서 'GUID_DEVCLASS_BATTERY' 라는 녀석이 정의되지 않아 찾을 수 없다고...

BatClass.h라는 파일을 찾아서 열어본다.
이런 저런 코드들이 보일텐데.. GUID_DEVCLASS_BATTERY를 검색해보면 없을 거이다. GUID_DEVCLASS_BATTERY를 추가시켜주어야 한다.
코드를 대충 보면 비슷한 녀석들이 모여있는 곳이 있다. 그곳에 다음을 넣어준다.
...
DEFINE_GUID( GUID_DEVCLASS_BATTERY,
                      0x72631E54, 0x78A4, 0x11D0, 0xBC, 0xF7, 0x00, 0xAA, 0x00, 0xB7, 0xB3, 0x2A);
...

구글에서 검색하다 찾았는데.. 위의 문장이 정의된 GUID_DEVCLASS_BATTERY 의 값인듯 하다.

이렇게 수정을 하고 컴파일을 다시 하면, 정상적으로 빌드가 될 것이고, 추가로 필요한 배터리의 정보는 소스의 내용을 수정해서 얻을 수 있을 것이다.

소스는 분석을 해봐야 더 정확한 것을 알 수 있을 듯한데.. 배터리 뿐만 아니라 여러 디바이스 드라이버의 정보를얻을 때에도 유용하게 쓰이는 듯 보인다.



2008. 9. 19. 19:05

하드디스크 용량 가져오기


GetDiskFreeSpaceEx() 라는 함수가 하드디스크의 총 용량, 사용 용량, 남은 용량을 가져오는 함수이다.

MSDN을 살펴보면 다음과 같이 함수가 정의되어 있다.
BOOL WINAPI GetDiskFreeSpaceEx(
  __in LPCTSTR lpDirectoryName,
  __out PULARGE_INTEGER lpFreeBytesAvailable,
  __out PULARGE_INTEGER lpTotalNumberOfByte,
  __out PULARGE_INTEGER lpTotalNumberOfFreeBytes
);

사용법은 직관적으로 함수의 인자를 보면 알 수 있을 것이다.
첫 번째 인자에 원하는 파티션의 경로(c:\, d:\ 등의)를 넣어준다. 그러면 나머지 인자에서 원하는 정보를 얻을 수 있다.

간단한 예제를 가지고 사용하는 방법을 알아본다. 나중에 필요할 때 대충 참고할 요령으로.. ^^;

ULARGE_INTEGER avail, total, free;
avail.QuadPart = 0L;
total.QuadPart = 0L;
free.QuadPart = 0L;
int m_avail, m_total, m_free;
TCHAR buf[125];

// C:\의 하드디스크 용량 정보를 받아올 것이다.
GetDiskFreeSpaceEx(TEXT("c:\\"), &avail, &total, &free);

// GByte 로 표현을 하기 위한 부분.. MByte는 숫자가 너무커서... -_-;
m_total = (int)(total.QuadPart>>30);
m_free = (int)(free.QuadPart>>30);

// 간단하게 메시지 박스로 출력을 해서 확인한다.
wsprintf(buf, TEXT("실제용량 %d GByte, 남은용량 %d GByte"), m_total, m_free);
MessageBox(hWnd, buf, TEXT("test"), MB_OK);
참고로 MByte 단위로 하드디스크의 용량을 계산하고자 한다면 아래와 같이 수정을 해주면 된다.
m_total = (int)(total.QuadPart >> 20);
m_free = (int)(free.QuadPart >> 20);

2008. 9. 4. 14:40

DriverEntry()



디바이스 드라이버가 최초로 시작되는 DriverEntry()에 대해 간단하게 알아보자!
이름 그대로 Driver Entry.. 드라이버의 엔트리(입장)이다. 일반적인 프로그램.. 예를 들의 C 프로그램에서 main()과 같은 역할을 하는 함수라고 보면 된다.

MSDN의 내용을 참고 하고 싶으면.. 여기클릭해서 보길 바람!!

드라이버는 I/O Manager에 의해 메모리에 로드(load)되어지고, I/O Manager는 DriverObject를 만들어 DriverEntry() 함수를 호출한다.
그리고 이 DriverEntry() 함수에서는 DriverObject를 초기화 해주는 작업을 진행하게 된다.
초기화 해주는 작업이란것은 드라이버의 I/O 요청에 의한 IRP를 처리해주는 핸들러(함수)를 초기화 해주는 것이라고 알면 될듯 하다.

다음은 WDM 드라이버인 kbfiltr(Keyboard Filter Driver)의 DriverEntry()이다.
NTSTATUS DriverEntry ( IN  PDRIVER_OBJECT  DriverObject,
                                   IN  PUNICODE_STRING RegistryPath )
{
    ULONG i;

    UNREFERENCED_PARAMETER (RegistryPath);

    for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) {
        DriverObject->MajorFunction[i] = KbFilter_DispatchPassThrough;
    }

    DriverObject->MajorFunction [IRP_MJ_CREATE] =
    DriverObject->MajorFunction [IRP_MJ_CLOSE] =        KbFilter_CreateClose;
    DriverObject->MajorFunction [IRP_MJ_PNP] =            KbFilter_PnP;
    DriverObject->MajorFunction [IRP_MJ_POWER] =       KbFilter_Power;
    DriverObject->MajorFunction [IRP_MJ_INTERNAL_DEVICE_CONTROL] =
                                                                                 KbFilter_InternIoCtl;
    DriverObject->DriverUnload = KbFilter_Unload;
    DriverObject->DriverExtension->AddDevice = KbFilter_AddDevice;

    return STATUS_SUCCESS;
}


하는 일을 보면, 인자로 넘어오는 DriverObject의 접근 가능한 필드를 채워넣는 작업을 하고 있다는 것을 알 수 있다.
IRP를 처리하기 위한 루틴들을 MajorFunction[]에 넣고 있다.
그리고 DriverExtension->AddDevice를 통해 AddDevice()를 호출한다.

WDM이 아닌 다른 방식의 드라이버의 DriverEntry()함수도 생긴 모습은 거의 동일하다.
다음은 Ctrl2Cap라는 함수의 DriverEntry() 이다.
NTSTATUS DriverEntry(IN PDRIVER_OBJECT  DriverObject, IN PUNICODE_STRING RegistryPath )
{
    ...
      
    ntStatus = IoCreateDevice (DriverObject,
                               0,
                               &deviceNameUnicodeString,
                               FILE_DEVICE_CTRL2CAP,
                               0,
                               TRUE,
                               &deviceObject );

    if (NT_SUCCESS(ntStatus)) {
        ....
        // Create dispatch points for all the IRPs the keyboard class device handles.
        DriverObject->MajorFunction[IRP_MJ_READ]                  = Ctrl2capDispatchRead;
        DriverObject->MajorFunction[IRP_MJ_CREATE]              =
        DriverObject->MajorFunction[IRP_MJ_CLOSE]                =
        DriverObject->MajorFunction[IRP_MJ_FLUSH_BUFFERS]  =
        DriverObject->MajorFunction[IRP_MJ_CLEANUP]             =
        DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = Ctrl2capDispatchGeneral;
    }
    ...
    return Ctrl2capInit( DriverObject );
}


대충 차이점을 보자면, WDM의 디바이스 드라이버는 DriverObject의 DeviceObject를 AddDevice에서 생성을하고, Ctrl2Cap와 같은 드라이버는 DriverEntry()에서 DeviceObject를 생성한다는 것... -_-;;

맞나 모르겠음...^^;

여튼 DriverEntry()의 하는 일은 현재 사용하고자 할 드라이버가 메모리에 적재될 때 , 디바이스 드라이버가 가지는 다양한 기능을 처리할 함수 엔트리들의 주소를 등록한다.


'Windows > Device Driver' 카테고리의 다른 글

키보드 스캔코드  (0) 2009.05.21
시스템 장치별 CLASS GUID  (0) 2009.02.17
DDK 다운로드, Windbg 사용...  (2) 2008.11.04
DEVICE_OBJECT  (0) 2008.09.04
DRIVER_OBJECT  (1) 2008.09.04
2008. 9. 4. 13:22

DEVICE_OBJECT



Windows Driver Kit: Kernel-Mode Driver Architecture
DEVICE_OBJECT
[This is preliminary documentation and subject to change.]

The DEVICE_OBJECT structure is used by the operating system to represent a device object. A device object represents a logical, virtual, or physical device for which a driver handles I/O requests.

typedef struct _DEVICE_OBJECT {
  CSHORT  Type;
  USHORT  Size;
  LONG  ReferenceCount;
  PDRIVER_OBJECT  DriverObject;
  PDEVICE_OBJECT  NextDevice;
  PDEVICE_OBJECT  AttachedDevice;
  PIRP  CurrentIrp;
  PIO_TIMER  Timer;
  ULONG  Flags;
  ULONG  Characteristics;
  __volatile PVPB  Vpb;
  PVOID  DeviceExtension;
  DEVICE_TYPE  DeviceType;
  CCHAR  StackSize;
  union {
    LIST_ENTRY  ListEntry;
    WAIT_CONTEXT_BLOCK  Wcb;
  } Queue;
  ULONG  AlignmentRequirement;
  KDEVICE_QUEUE  DeviceQueue;
  KDPC  Dpc;
  ULONG  ActiveThreadCount;
  PSECURITY_DESCRIPTOR  SecurityDescriptor;
  KEVENT  DeviceLock;
  USHORT  SectorSize;
  USHORT  Spare1;
  PDEVOBJ_EXTENSION  DeviceObjectExtension;
  PVOID  Reserved;
} DEVICE_OBJECT, *PDEVICE_OBJECT;

Members

Type
Used by the operating system to indicate that an object is a device object. For device objects, the value of this member is 3. This is a read-only member.

Size
Specifies the size, in bytes, of the device object. This size does not include the device object extension, if present (see DeviceExtension later in this topic). This is a read-only member.

ReferenceCount
Used by the I/O manager to track the number of open handles for the device that are associated with the device object. This allows the I/O manager to avoid unloading a driver when there are outstanding handles for the driver's device(s). This is a read-only member.

DriverObject
A pointer to the driver object (DRIVER_OBJECT), that reprensents the loaded image of the driver that was input to the DriverEntry and AddDevice routines. This member is set by the I/O manager upon a successful call to IoCreateDevice or IoCreateDeviceSecure. This is a read-only member.

NextDevice
A pointer to the next device object, if any, that was created by the same driver. The I/O manager updates this list at each successful call to IoCreateDevice or IoCreateDeviceSecure.

A non- Plug and Play (PnP) driver that is being unloaded must traverse (“walk”) the list of its device objects and delete them. A PnP driver does not have to walk this list of device objects. Instead, PnP drivers perform their cleanup during the device removal PnP operation (IRP_MN_REMOVE_DEVICE).

A driver that recreates its device objects dynamically also uses this member. This is a read/write member.

AttachedDevice
A pointer to the attached device object. If there is no attached device object, this member is NULL. The device object that is pointed to by the AttachedDevice member typically is the device object of a filter driver, which intercepts I/O requests originally targeted to the device represent by the device object. For more information, see the IoAttachDevice and IoAttachDeviceByPointer topics. This is an opaque member.

CurrentIrp
A pointer to the current IRP if the driver has a StartIo routine whose entry point was set in the driver object and if the driver is currently processing IRP(s). Otherwise, this member is NULL. For more information, see the IoStartPacket and IoStartNextPacket topics. This is a read-only member.

Timer
A pointer to a timer object. This allows the I/O manager to call a driver-supplied timer routine every second. For more information, see IoInitializeTimer. This is a read/write member.

Flags
Device drivers perform a bitwise OR operation with this member in their newly created device objects by using one or more of the following system-defined values:
DO_BUFFERED_IO or DO_DIRECT_IO
Specifies the type of buffering that is used by the I/O manager for I/O requests that are sent to the device stack. Higher-level drivers OR this member with the same value as the next-lower driver in the stack, except possibly for highest-level drivers.
DO_BUS_ENUMERATED_DEVICE
The operating system sets this flag in each physical device object (PDO). Drivers must not modify this flag.
DO_DEVICE_INITIALIZING
The I/O manager sets this flag when it creates the device object. A device function driver or filter driver clears the flag in its AddDevice routine, after it does the following:
  • Attaches the device object to the device stack.
  • Establishes the device power state.
  • Performs a bitwise OR operation on the member with one of the power flags (if it is necessary).

it and The Plug and Play (PnP) manager checks that the flag is clear after the AddDevice routine returns.

DO_EXCLUSIVE
Indicates that the driver services an exclusive device, such as a video, serial, parallel, or sound device. WDM drivers must not set this flag. For more information, see the Specifying Exclusive Access to Device Objects topic.
DO_MAP_IO_BUFFER
This flag is no longer used. Drivers should not set this flag.
DO_POWER_INRUSH
Drivers of devices that require inrush current when the device is turned on must set this flag. A driver cannot set both this flag and DO_POWER_PAGABLE.
DO_POWER_PAGABLE
Pageable drivers that are compatible with Microsoft Windows 2000 and later versions of Windows, are not part of the paging path, and do not require inrush current must set this flag. The system calls such drivers at IRQL = PASSIVE_LEVEL. Drivers cannot set both this flag and DO_POWER_INRUSH. All drivers for WDM, Microsoft Windows 98, and Windows Millennium Edition must set DO_POWER_PAGABLE.
DO_SHUTDOWN_REGISTERED
Used by the I/O manager to indicate that a driver has registered the device object for shutdown notifications. This flag should not be used by drivers.
DO_VERIFY_VOLUME
Removable-media drivers set this flag while they process transfer requests. Such drivers should also check for this flag in the target for a transfer request before they transfer any data. For more information, see the Supporting Removable Media topic.

For more information about how to set the Flags member, see Initializing a Device Object.

Characteristics
Specifies one or more system-defined constants, combined with a bitwise OR operation, that provide additional information about the driver's device. These constants include the following:
FILE_AUTOGENERATED_DEVICE_NAME
Directs the I/O manager to generate a name for the device, instead of the caller specifying a DeviceName when it calls this routine. The I/O manager makes sure that the name is unique. This characteristic is typically specified by a PnP bus driver to generate a name for a physical device object (PDO) for a child device on the same bus. This characteristic is new starting with Microsoft Windows 2000 and Microsoft Windows 98.
FILE_CHARACTERISTIC_PNP_DEVICE
Indicates that the device object is part of a Plug and Play (PnP) stack. This characteristic is required if a bus driver (or bus filter driver) registers WMI support for a device object that has not yet received the IRP_MN_START_DEVICE request. FILE_CHARACTERISTIC_PNP_DEVICE is also required if a function or filter driver registers for WMI before attaching to its device stack.
FILE_CHARACTERISTIC_TS_DEVICE
Indicates that the device object is part of a Terminal Services device stack. Drivers should not set this characteristic.
FILE_CHARACTERISTIC_WEBDAV_DEVICE
Indicates that a Web-based Distributed Authoring and Versioning (WebDAV) file system is mounted on the device. Drivers should not set this characteristic.
FILE_DEVICE_IS_MOUNTED
Indicates that a file system is mounted on the device. Drivers should not set this characteristic.
FILE_DEVICE_SECURE_OPEN
(Microsoft Windows NT 4.0 with Service Pack 5 (SP5) and later versions of Windows)

Directs the I/O manager to apply the security descriptor of the device object to relative opens and trailing file name opens for the device. For more information, see the Controlling Device Namespace Access topic.

FILE_FLOPPY_DISKETTE
Indicates that the device is a floppy disk device.
FILE_READ_ONLY_DEVICE
Indicates that the device cannot be written to.
FILE_REMOTE_DEVICE
Indicates that the device is remote.
FILE_REMOVABLE_MEDIA
Indicates that the storage device supports removable media. Notice that this characteristic indicates removable media, not a removable device. For example, drivers for JAZ drive devices should specify this characteristic, but drivers for PCMCIA flash disks should not.
FILE_VIRTUAL_VOLUME
Indicates that the volume is virtual. Drivers should not set this characteristic.
FILE_WRITE_ONCE_MEDIA
Indicates that the device supports write-once media. Drivers do not set this member directly. For more information about how to set device characteristics, see the Specifying Device Characteristics topic.

Vpb
A pointer to the volume parameter block (VPB) that is associated with the device object. For file system drivers, the VPB can provide a connection to any unnamed logical device object that represents an instance of a mounted volume. This is an opaque member.

DeviceExtension
A pointer to the device extension. The structure and contents of the device extension are driver-defined. The size is driver-determined, specified in the driver's call to IoCreateDevice or IoCreateDeviceSecure. For more information about device extensions, see Device Extensions. This is a read-only member. However, the object that the member points to can be modified by the driver.

DeviceType
Set by IoCreateDevice and IoCreateDeviceSecure by using the value that is specified for that routine's DeviceType parameter. For more information, see the Specifying Device Types topic.

StackSize
Specifies the minimum number of stack locations in IRPs to be sent to this driver. IoCreateDevice and IoCreateDeviceSecure set this member to 1 in newly created device objects; lowest-level drivers can therefore ignore this member. The I/O manager automatically sets the StackSize member in a higher-level driver's device object to the appropriate value if the driver calls IoAttachDevice or IoAttachDeviceToDeviceStack. Only a higher-level driver that chains itself over another driver with IoGetDeviceObjectPointer must explicitly set the value of StackSize in its own device object(s) to 1 + the StackSize value of the next-lower driver's device object.

Queue
Used internally by the I/O manager to queue the device object when it is required. This is an opaque member.

AlignmentRequirement
Specifies the device's address alignment requirement for data transfers. The value must be one of the FILE_XXX_ALIGNMENT values that are defined in Wdm.h. For more information, see the Initializing a Device Object, GetDmaAlignment, and ZwQueryInformationFile topics.

DeviceQueue
The device queue object for the device object. The device queue object contains any IRPs that are waiting to be processed by the driver that is associated with the device object. For more information, see the Driver-Managed IRP Queues topic. This is an opaque member.

Dpc
The deferred procedure call (DPC) object for the device object. For more information, see the Introduction to DPC Objects topic. This is an opaque member.

ActiveThreadCount
Reserved for future use. This is an opaque member.

SecurityDescriptor
Specifies a security descriptor (SECURITY_DESCRIPTOR) for the device object when the device object is created. If this member is NULL, the device object receives default security settings. This is a read-only member, although the member can be modified through the ZwSetSecurityObjectfunction.

DeviceLock
A synchronization event object that is allocated by the I/O manager. The I/O manager obtains his event object before it dispatches a mount or mount-verify request to a file-system driver. This is an opaque member.

SectorSize
If the device object does not represent a volume, this member is set to zero. If the device object represents a volume, this member specifies the volume’s sector size, in bytes. The I/O manager uses this member to make sure that all read operations, write operations, and set file position operations that are issued are aligned correctly when intermediate buffering is disabled. A default system bytes-per-sector value is used when the device object is created, however, file system drivers; and more rarely, legacy and minifilter drivers, can update this value that is based on the geometry of the underlying volume hardware when a mount occurs. Other drivers should not modify this member.

Spare1
Reserved for system use. This is an opaque member.

DeviceObjectExtension
A pointer to a device object extension that is used by the I/O manager and PnP manager to store information about the state of the device. This is an opaque member.

Reserved
Reserved for system use. This is an opaque member.

Comments

The operating system represents devices by device objects. For more information, see the Device Objects and Device Stacks topic.

Drivers create device objects by using the IoCreateDevice and IoCreateDeviceSecure routines. For more information about how to create device objects, see Creating a Device Object.

A device object is partially opaque. Drivers do not set members of the device object directly, unless otherwise documented. For more information about the members that drivers can modify directly, see Initializing a Device Object. For information about other device object properties, see Properties of Device Objects.

Opaque members within a device object must be considered inaccessible. Drivers that have dependencies on object member locations or access to opaque members might not remain portable and interoperable with other drivers over time.

The system-supplied video port driver sets up the fields of the device objects that it creates on behalf of video miniport drivers.

The system-supplied SCSI port driver sets up the fields of the device objects that it creates on behalf of SCSI miniport drivers.

The system-supplied NDIS library sets up the fields of the device objects that it creates on behalf of NDIS miniport drivers.

Requirements

Headers: Defined in Wdm.h. Include Wdm.h, Ntddk.h, Ntifs.h, or Fltkernel.h.

See Also

DRIVER_OBJECT, IoAttachDevice, IoAttachDeviceToDeviceStack, IoCreateDevice, IoDeleteDevice, IoGetDeviceObjectPointer

APIScan Requirements

Header: Wdm.h, Ntddk.h, Ntifs.h
Function: DEVICE_OBJECT

출처 : MSDN


'Windows > Device Driver' 카테고리의 다른 글

키보드 스캔코드  (0) 2009.05.21
시스템 장치별 CLASS GUID  (0) 2009.02.17
DDK 다운로드, Windbg 사용...  (2) 2008.11.04
DriverEntry()  (0) 2008.09.04
DRIVER_OBJECT  (1) 2008.09.04
2008. 9. 4. 11:48

DRIVER_OBJECT



디바이스 드라이버라는 것을 다루고 있다.
이쪽에 대해서는 정말이지 무지하다. 그래서 어렵다. 그래서 공부를 하려한다. 아... -_-;
여기저기 자료 찾고 알때까지.. 잘 할 수 있을 때까지 한번 해보려 한다.
일단 개념부터 정리해나가고.. 보자는.. ^^;

다음은 DRIVER_OBJECT에 대한 MSDN의 내용이다.

Windows Driver Kit: Kernel-Mode Driver Architecture
DRIVER_OBJECT

Each driver object represents the image of a loaded kernel-mode driver. A pointer to the driver object is an input parameter to a driver's DriverEntry, AddDevice, and optional Reinitialize routines and to its Unload routine, if any.

A driver object is partially opaque. Driver writers must know about certain members of a driver object to initialize a driver and to unload it if the driver is unloadable. The following members of the driver object are accessible to drivers.


Accessible Members

PDEVICE_OBJECT DeviceObject
Pointer to the device objects created by the driver. This member is automatically updated when the driver calls IoCreateDevice successfully. A driver can use this member and the NextDevice member of DEVICE_OBJECT to step through a list of all the device objects that the driver created.

PDRIVER_EXTENSION DriverExtension
Pointer to the driver extension. The only accessible member of the driver extension is DriverExtension->AddDevice, into which a driver's DriverEntry routine stores the driver's AddDevice routine.

PUNICODE_STRING HardwareDatabase
Pointer to the \Registry\Machine\Hardware path to the hardware configuration information in the registry.

PFAST_IO_DISPATCH FastIoDispatch
Pointer to a structure defining the driver's fast I/O entry points. This member is used only by FSDs and network transport drivers.

PDRIVER_INITIALIZE DriverInit
The entry point for the DriverEntry routine, which is set up by the I/O manager.

PDRIVER_STARTIO DriverStartIo
The entry point for the driver's StartIo routine, if any, which is set by the DriverEntry routine when the driver initializes. If a driver has no StartIo routine, this member is NULL.

PDRIVER_UNLOAD DriverUnload
The entry point for the driver's Unload routine, if any, which is set by the DriverEntry routine when the driver initializes. If a driver has no Unload routine, this member is NULL.

PDRIVER_DISPATCH MajorFunction[IRP_MJ_MAXIMUM_FUNCTION+1]
A dispatch table consisting of an array of entry points for the driver's DispatchXxx routines. The array's index values are the IRP_MJ_Xxx values representing each IRP major function code. Each driver must set entry points in this array for the IRP_MJ_Xxx requests that the driver handles. For more information, see Writing Dispatch Routines. Each DispatchXxx routine is declared as follows:

NTSTATUS
(*PDRIVER_DISPATCH) (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp
    );

Comments

Each kernel-mode driver's initialization routine should be named DriverEntry so the system will load the driver automatically. If this routine's name is something else, the driver writer must define the name of the initialization routine for the linker; otherwise, the system loader or I/O manager cannot find the driver's transfer address. The names of other standard driver routines can be chosen at the discretion of the driver writer.

A driver must set its DispatchXxx entry points in the driver object that is passed in to the DriverEntry routine when the driver is loaded. A device driver must set one or more DispatchXxx entry points for the IRP_MJ_XXX that any driver of the same type of device is required to handle. A higher-level driver must set one or more DispatchXxx entry points for all the IRP_MJ_XXX that it must pass on to the underlying device driver. Otherwise, a driver is not sent IRPs for any IRP_MJ_XXX for which it does not set up a DispatchXxx routine in the driver object. For more information about the set of IRP_MJ_XXX that drivers for different types of underlying devices are required to handle, see IRP Major Function Codes.

The DriverEntry routine also sets the driver's AddDevice, StartIo and/or Unload entry points, if any, in the driver object.

The HardwareDatabase string can be used by device drivers to get hardware configuration information from the registry when the driver is loaded. A driver is given read-only access to this string.

The RegistryPath input to the DriverEntry routine points to the \Registry\Machine\System\CurrentControlSet\Services\DriverName key, where the value entry of DriverName identifies the driver. As for the HardwareDatabase in the input driver object, a driver is given read-only access to this string.

Undocumented members within a driver object should be considered inaccessible. Drivers with dependencies on object member locations or on access to undocumented members might not remain portable and interoperable with other drivers over time.

Requirements

Headers: Defined in Wdm.h. Include Wdm.h, Ntddk.h, or Ntifs.h.

See Also

DriverEntry, IoCreateDevice, IoDeleteDevice, StartIo, Unload

APIScan Requirements

Header: Wdm.h, Ntddk.h, Ntifs.h
Function: DRIVER_OBJECT

출처 : MSDN

'Windows > Device Driver' 카테고리의 다른 글

키보드 스캔코드  (0) 2009.05.21
시스템 장치별 CLASS GUID  (0) 2009.02.17
DDK 다운로드, Windbg 사용...  (2) 2008.11.04
DriverEntry()  (0) 2008.09.04
DEVICE_OBJECT  (0) 2008.09.04
2008. 8. 20. 10:52

GetCurrentDirectory()를 이용한 Windows에서 현재경로 받아오기..



Windows에서 현재 실행되는 프로그램의 현재 작업 디렉토리를 알아오기 위해 "GetCurrentDirectory()"를 사용한다.

첫번 째 인자로 경로를 표시할 문자열의 길이를 넣어주고, 두번 째 인자로 실제 받아온 경로를 보여준다.

간단히 예를 들면...
char Path[255];

GetCurrentDirectory(255, Path);
printf("Current Path is %s\n", Path);

이렇게 하면 콘솔창에서 현재 위의 프로그램의 경로를 확인할 수 있다.

MSDN을 검색하니 다음과 같이 되어있다.

GetCurrentDirectory Function

Retrieves the current directory for the current process.

Syntax

DWORD WINAPI GetCurrentDirectory(
__in DWORD nBufferLength,
__out LPTSTR lpBuffer
);

Parameters

nBufferLength [in]

The length of the buffer for the current directory string, in TCHARs. The buffer length must include room for a terminating null character.

lpBuffer [out]

A pointer to the buffer that receives the current directory string. This null-terminated string specifies the absolute path to the current directory.

To determine the required buffer size, set this parameter to NULL and the nBufferLength parameter to 0.

Return Value

If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character.

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

If the buffer that is pointed to by lpBuffer is not large enough, the return value specifies the required size of the buffer, in characters, including the null-terminating character.

Remarks

Each process has a single current directory that consists of two parts:

  • A disk designator that is either a drive letter followed by a colon, or a server name followed by a share name (\\servername\sharename)
  • A directory on the disk designator

To set the current directory, use the SetCurrentDirectory function.

In certain rare cases, if the specified directory is on the current drive, the function might omit the drive letter and colon from the path. Therefore, the size that is returned by the function might be two characters less than the size of the specified string, not including the terminating null character. This behavior might occur in edge situations such as in a services application. If you need the drive letter, make a subsequent call to GetFullPathName to retrieve the drive letter.

Examples

For an example, see Changing the Current Directory.

Requirements

Client Requires Windows Vista, Windows XP, or Windows 2000 Professional.
Server Requires Windows Server 2008, Windows Server 2003, or Windows 2000 Server.
Header

Declared in WinBase.h; include Windows.h.

Library

Use Kernel32.lib.

DLL

Requires Kernel32.dll.

Unicode/ANSI

Implemented as GetCurrentDirectoryW (Unicode) and GetCurrentDirectoryA (ANSI).



2008. 7. 28. 11:30

MSDN 키보드 입력 작동 방식 스크랩


키보드 입력 작동 방식

 

Windows Forms에서는 Windows 메시지에 대한 응답으로 키보드 이벤트를 발생시켜 키보드 입력을 처리합니다. 대부분의 Windows Forms 응용 프로그램에서는 키보드 이벤트를 처리하여 키보드 입력을 단독으로 처리합니다. 그러나 키가 컨트롤에 도달하기 전에 키를 가로채는 등의 고급 키보드 입력 시나리오를 구현하려면 키보드 메시지가 작동하는 방식을 알아야 합니다. 이 항목에서는 Windows Forms에서 인식하는 키 데이터 형식을 설명하고 키보드 메시지가 라우팅되는 방법에 대한 개요를 설명합니다. 키보드 이벤트에 대한 자세한 내용은 키보드 이벤트 사용을 참조하십시오.

 

키 형식

Windows Forms에서는 키보드 입력을 비트 Keys 열거형으로 나타내는 가상 키 코드로 식별합니다. Keys 열거형을 사용하면 눌려진 일련의 키를 결합하여 단일 값을 만들 수 있습니다. 이러한 값은 WM_KEYDOWN WM_SYSKEYDOWN Windows 메시지와 함께 제공되는 값에 해당합니다. KeyDown 또는 KeyUp 이벤트를 처리하여 실제로 눌려진 키를 대부분 감지할 수 있습니다. 문자 키는 Keys 열거형의 하위 집합이며 WM_CHAR WM_SYSCHAR Windows 메시지와 함께 제공되는 값에 해당합니다. 눌려진 키를 결합하여 문자가 만들어지는 경우에는 KeyPress 이벤트를 처리하여 해당 문자를 감지할 수 있습니다. 또는 Visual Basic 프로그래밍 인터페이스에서 노출되는 Keyboard를 사용하여 눌려진 키를 확인하고 키를 보낼 수 있습니다. 자세한 내용은 키보드에 액세스를 참조하십시오.

 

키보드 이벤트의 순서

앞에서 설명한 대로 한 컨트롤에서 발생할 수 있는 키보드 관련 이벤트는 세 가지입니다. 다음 시퀀스는 키보드 이벤트의 일반적인 순서를 보여 줍니다.

  • 사용자가 "a" 키를 누르면 해당 키가 전처리되고 디스패치된 다음 KeyDown 이벤트가 발생합니다.

  • 사용자가 "a" 키를 누르고 있으면 해당 키가 전처리되고 디스패치된 다음 KeyPress 이벤트가 발생합니다.

  • 이 이벤트는 사용자가 키를 누르고 있을 때 여러 차례 발생합니다.

  • 사용자가 "a" 키를 놓으면 해당 키가 전처리되고 디스패치된 다음 KeyUp 이벤트가 발생합니다.

 

키 전처리

다른 메시지와 마찬가지로 키보드 메시지는 폼이나 컨트롤의 WndProc 메서드에서 처리됩니다. 그러나 키보드 메시지를 처리하기 전에 PreProcessMessage 메서드는 특수 문자 키와 실제 키를 처리하도록 재정의할 수 있는 메서드를 하나 이상 호출합니다. 이러한 메서드를 재정의하여 컨트롤에서 메시지를 처리하기 전에 특정 키를 감지하고 필터링할 수 있습니다. 다음 표에서는 수행할 작업과 발생하는 관련 메서드를 메서드 발생 순서에 따라 보여 줍니다.

 

KeyDown 이벤트의 전처리

작업

관련 메서드

설명

액셀러레이터 키나 메뉴 바로 가기 같은 명령 키를 확인합니다.

ProcessCmdKey

이 메서드는 일반 키보다 우선되는 명령 키를 처리합니다. 이 메서드가 true를 반환하는 경우 키 메시지가 디스패치되지 않고 키 이벤트도 발생하지 않습니다. false를 반환하는 경우에는 IsInputKey가 호출됩니다.

전처리가 필요한 특수 키인지 아니면 KeyDown 이벤트를 발생시켜 컨트롤에 디스패치해야 하는 일반 문자인지 여부를 확인합니다.

IsInputKey

이 메서드가 true를 반환하는 경우에는 컨트롤이 일반 문자이고 KeyDown 이벤트가 발생합니다. false를 반환하는 경우에는 ProcessDialogKey가 호출됩니다.

Note참고

컨트롤에서 키나 키 조합을 받도록 하려면 PreviewKeyDown 이벤트를 처리한 다음 원하는 키나 키 조합에 대해 PreviewKeyDownEventArgsIsInputKeytrue로 설정합니다.

키가 탐색 키(Esc, Tab, Enter 또는 화살표 키)인지 여부를 확인합니다.

ProcessDialogKey

이 메서드는 컨트롤 내에서 컨트롤과 부모 컨트롤 간의 포커스 전환과 같은 특수 기능을 담당하는 실제 키를 처리합니다. 현재 컨트롤에서 키를 처리하지 않으면 ProcessDialogKey가 부모 컨트롤에서 호출되고 계층 구조의 최상위 컨트롤에까지 이같은 호출 방식이 적용됩니다. 이 메서드에서 true를 반환하면 전처리는 완료되지만 키 이벤트는 생성되지 않습니다. false를 반환하면 KeyDown 이벤트가 발생합니다.

 

KeyPress 이벤트의 전처리

작업

관련 메서드

설명

키가 컨트롤에서 전처리 되어야 하는 일반 문자인지 여부를 확인합니다.

IsInputChar

문자가 일반 문자인 경우 이 메서드는 true를 반환하고 KeyPress 이벤트가 발생하지만 추가적인 전처리 작업은 발생하지 않습니다. 일반 문자가 아닌 경우에는 ProcessDialogChar가 호출됩니다.

문자가 단추의 &OK와 같은 니모닉인지 여부를 확인 합니다.

ProcessDialogChar

이 메서드는 ProcessDialogKey와 비슷하게 컨트롤 계층 구조를 올라가며 호출됩니다. 컨트롤이 컨테이너 컨트롤인 경우 이 메서드는 컨트롤과 그 자식 컨트롤에 대해 ProcessMnemonic을 호출하여 니모닉을 확인합니다. ProcessDialogChartrue를 반환하는 경우 KeyPress 이벤트가 발생하지 않습니다.

 

키보드 메시지 전처리

폼이나 컨트롤의 WndProc 메서드에 도달한 키보드 메시지는 재정의할 수 있는 메서드 집합에 의해 처리됩니다. 이러한 메서드는 각각 키보드 메시지가 처리되어 컨트롤에서 사용되었는지 여부를 지정하는 Boolean 값을 반환합니다. 이러한 메서드 중 한 메서드에서 true가 반환되면 해당 메시지가 처리된 것으로 간주되므로 추가 처리를 위해 컨트롤의 기본 또는 부모에 메시지가 전달되지 않습니다. 그렇지 않은 경우에는 메시지가 메시지 큐에 유지되고 컨트롤의 기본 또는 부모의 다른 메서드에서 처리됩니다. 다음 표에서는 키보드 메시지를 처리하는 메서드를 보여 줍니다.

메서드

설명

ProcessKeyMessage

이 메서드는 컨트롤의 WndProc 메서드에서 받은 모든 키보드 메시지를 처리합니다.

ProcessKeyPreview

이 메서드는 키보드 메시지를 컨트롤의 부모에게 보냅니다. ProcessKeyPreviewtrue를 반환하면 키 이벤트가 생성되지 않고, 그렇지 않은 경우에는 ProcessKeyEventArgs가 호출됩니다.

ProcessKeyEventArgs

이 메서드는 KeyDown, KeyPress KeyUp 이벤트를 적절하게 발생시킵니다.

 

키보드 메서드 재정의

키보드 메시지를 전처리하고 처리할 때 재정의할 수 있는 여러 가지 메서드가 있지만 그 중 다음과 같은 메서드가 특히 많이 사용됩니다. 다음 표에서는 수행할 작업과 키보드 메서드를 재정의할 수 있는 가장 좋은 방법을 보여 줍니다.

작업

메서드

탐색 키를 가로채고 KeyDown 이벤트를 발생시킵니다. 예를 들어 Tab 키와 Enter 키를 텍스트 상자에서 처리해야 할 수 있습니다.

IsInputKey를 재정의합니다.

컨트롤에서 특수 입력 키나 탐색 키에 대한 처리를 수행합니다. 예를 들어, 목록 컨트롤에서 화살표 키를 사용하여 선택한 항목을 변경할 수 있습니다.

ProcessDialogKey를 재정의합니다.

탐색 키를 가로채고 KeyPress 이벤트를 발생시킵니다. 예를 들어, 스핀 상자 컨트롤에서 화살표 키를 여러 차례 눌러 항목 전체를 빠르게 진행할 수 있습니다.

IsInputChar를 재정의합니다.

KeyPress 이벤트 중 특수 입력 키나 탐색 키에 대한 처리를 수행합니다. 예를 들어, 목록 컨트롤에서 "r" 키를 누른 채로 r 문자로 시작하는 항목 사이를 건너뛸 수 있습니다.

ProcessDialogChar를 재정의합니다.

사용자 지정 니모닉 처리를 수행합니다. 예를 들어, 도구 모음에 포함된 소유자가 그린 단추의 니모닉을 처리할 수 있습니다.

ProcessMnemonic를 재정의합니다.

 

참고 항목

참조

My.Computer.Keyboard 개체
Keys
WndProc
PreProcessMessage

개념

키보드에 액세스
키보드 이벤트 사용