Win32 API 日本語リファレンス
ホームUI.WindowsAndMessaging › RegisterDeviceNotificationW

RegisterDeviceNotificationW

関数
デバイス変更通知の受信を登録する(Unicode)。
DLLUSER32.dll文字セットUnicode (-W)呼出規約winapiSetLastErrorあり対応OSWindows XP 以降

シグネチャ

// USER32.dll  (Unicode / -W)
#include <windows.h>

HDEVNOTIFY RegisterDeviceNotificationW(
    HANDLE hRecipient,
    void* NotificationFilter,
    REGISTER_NOTIFICATION_FLAGS Flags
);

パラメーター

名前方向説明
hRecipientHANDLEin

NotificationFilter パラメーターで指定されたデバイスに関するデバイスイベントを受け取る、ウィンドウまたはサービスへのハンドルです。同じウィンドウハンドルを RegisterDeviceNotification の複数回の呼び出しで使用できます。

サービスはウィンドウハンドルまたはサービス状態ハンドルのいずれかを指定できます。

NotificationFiltervoid*in通知を送信する対象となるデバイスの種類を指定するデータブロックへのポインターです。このブロックは常に DEV_BROADCAST_HDR 構造体で始まります。このヘッダーに続くデータは dbch_devicetype メンバーの値に依存し、その値は DBT_DEVTYP_DEVICEINTERFACE または DBT_DEVTYP_HANDLE になります。詳細については「解説」を参照してください。
FlagsREGISTER_NOTIFICATION_FLAGSin

このパラメーターには次のいずれかの値を指定できます。

意味
DEVICE_NOTIFY_WINDOW_HANDLE
0x00000000
hRecipient パラメーターはウィンドウハンドルです。
DEVICE_NOTIFY_SERVICE_HANDLE
0x00000001
hRecipient パラメーターはサービス状態ハンドルです。

さらに、次の値を指定することもできます。

意味
DEVICE_NOTIFY_ALL_INTERFACE_CLASSES
0x00000004
すべてのデバイスインターフェイスクラスについて、受信側にデバイスインターフェイスイベントを通知します。(dbcc_classguid メンバーは無視されます。)

この値は dbch_devicetype メンバーが DBT_DEVTYP_DEVICEINTERFACE の場合にのみ使用できます。

戻り値の型: HDEVNOTIFY

公式ドキュメント

ウィンドウが通知を受け取る対象となるデバイス、またはデバイスの種類を登録します。(Unicode)

戻り値

関数が成功した場合、戻り値はデバイス通知ハンドルです。

関数が失敗した場合、戻り値は NULL です。拡張エラー情報を取得するには、GetLastError を呼び出します。

解説(Remarks)

アプリケーションは BroadcastSystemMessage 関数を使用してイベント通知を送信します。トップレベルウィンドウを持つアプリケーションは、 WM_DEVICECHANGE メッセージを処理することで基本的な通知を受け取ることができます。アプリケーションは RegisterDeviceNotification 関数を使用して、デバイス通知を受け取るための登録を行えます。

サービスは RegisterDeviceNotification 関数を使用して、デバイス通知を受け取るための登録を行えます。サービスが hRecipient パラメーターにウィンドウハンドルを指定した場合、通知はウィンドウプロシージャに送信されます。 hRecipient がサービス状態ハンドルの場合、 SERVICE_CONTROL_DEVICEEVENT 通知がサービスコントロールハンドラーに送信されます。サービスコントロールハンドラーの詳細については、 HandlerEx を参照してください。

プラグアンドプレイのデバイスイベントは、できるだけ速やかに処理してください。そうしないと、システムが応答しなくなる可能性があります。イベントハンドラーが実行をブロックする可能性のある処理(I/O など)を行う場合は、別のスレッドを開始してその処理を非同期に実行することをお勧めします。

RegisterDeviceNotification が返すデバイス通知ハンドルは、不要になったときに UnregisterDeviceNotification 関数を呼び出して閉じる必要があります。

DBT_DEVICEARRIVAL および DBT_DEVICEREMOVECOMPLETE イベントは、ポートデバイスについてはすべてのトップレベルウィンドウに自動的にブロードキャストされます。そのため、ポートに対して RegisterDeviceNotification を呼び出す必要はなく、dbch_devicetype メンバーが DBT_DEVTYP_PORT の場合、この関数は失敗します。ボリューム通知もトップレベルウィンドウにブロードキャストされるため、dbch_devicetypeDBT_DEVTYP_VOLUME の場合も関数は失敗します。 OEM 定義デバイスはシステムによって直接使用されないため、dbch_devicetypeDBT_DEVTYP_OEM の場合も関数は失敗します。

例については、 デバイス通知の登録を参照してください。

メモ

winuser.h ヘッダーは、UNICODE プリプロセッサ定数の定義に基づいて、この関数の ANSI 版または Unicode 版を自動的に選択するエイリアスとして RegisterDeviceNotification を定義します。エンコーディング中立のエイリアスの使用を、エンコーディング中立でないコードと混在させると、不整合が生じ、コンパイルエラーまたは実行時エラーの原因となることがあります。詳細については、関数プロトタイプの規則を参照してください。

出典・ライセンス: 上記「公式ドキュメント」の内容は Microsoft の Win32 API ドキュメント(MicrosoftDocs/sdk-api)を日本語に翻訳・改変したものです。© Microsoft Corporation. CC BY 4.0 で提供。
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)

各言語での呼び出し定義

// USER32.dll  (Unicode / -W)
#include <windows.h>

HDEVNOTIFY RegisterDeviceNotificationW(
    HANDLE hRecipient,
    void* NotificationFilter,
    REGISTER_NOTIFICATION_FLAGS Flags
);
[DllImport("USER32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
static extern IntPtr RegisterDeviceNotificationW(
    IntPtr hRecipient,   // HANDLE
    IntPtr NotificationFilter,   // void*
    uint Flags   // REGISTER_NOTIFICATION_FLAGS
);
<DllImport("USER32.dll", CharSet:=CharSet.Unicode, SetLastError:=True, ExactSpelling:=True)>
Public Shared Function RegisterDeviceNotificationW(
    hRecipient As IntPtr,   ' HANDLE
    NotificationFilter As IntPtr,   ' void*
    Flags As UInteger   ' REGISTER_NOTIFICATION_FLAGS
) As IntPtr
End Function
' hRecipient : HANDLE
' NotificationFilter : void*
' Flags : REGISTER_NOTIFICATION_FLAGS
Declare PtrSafe Function RegisterDeviceNotificationW Lib "user32" ( _
    ByVal hRecipient As LongPtr, _
    ByVal NotificationFilter As LongPtr, _
    ByVal Flags As Long) As LongPtr
' Unicode(W): 文字列は ByVal As LongPtr とし StrPtr(unicodeStr) を渡す
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

RegisterDeviceNotificationW = ctypes.windll.user32.RegisterDeviceNotificationW
RegisterDeviceNotificationW.restype = ctypes.c_void_p
RegisterDeviceNotificationW.argtypes = [
    wintypes.HANDLE,  # hRecipient : HANDLE
    ctypes.POINTER(None),  # NotificationFilter : void*
    wintypes.DWORD,  # Flags : REGISTER_NOTIFICATION_FLAGS
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('USER32.dll')
RegisterDeviceNotificationW = Fiddle::Function.new(
  lib['RegisterDeviceNotificationW'],
  [
    Fiddle::TYPE_VOIDP,  # hRecipient : HANDLE
    Fiddle::TYPE_VOIDP,  # NotificationFilter : void*
    -Fiddle::TYPE_INT,  # Flags : REGISTER_NOTIFICATION_FLAGS
  ],
  Fiddle::TYPE_VOIDP)
# Wide strings: pass str.encode("UTF-16LE") + "\x00\x00"
#[link(name = "user32")]
extern "system" {
    fn RegisterDeviceNotificationW(
        hRecipient: *mut core::ffi::c_void,  // HANDLE
        NotificationFilter: *mut (),  // void*
        Flags: u32  // REGISTER_NOTIFICATION_FLAGS
    ) -> *mut core::ffi::c_void;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[DllImport("USER32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr RegisterDeviceNotificationW(IntPtr hRecipient, IntPtr NotificationFilter, uint Flags);
"@
$api = Add-Type -MemberDefinition $sig -Name 'USER32_RegisterDeviceNotificationW' -Namespace Win32 -PassThru
# $api::RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags)
#uselib "USER32.dll"
#func global RegisterDeviceNotificationW "RegisterDeviceNotificationW" wptr, wptr, wptr
; RegisterDeviceNotificationW hRecipient, NotificationFilter, Flags   ; 戻り値は stat
; hRecipient : HANDLE -> "wptr"
; NotificationFilter : void* -> "wptr"
; Flags : REGISTER_NOTIFICATION_FLAGS -> "wptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
#uselib "USER32.dll"
#cfunc global RegisterDeviceNotificationW "RegisterDeviceNotificationW" sptr, sptr, int
; res = RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags)
; hRecipient : HANDLE -> "sptr"
; NotificationFilter : void* -> "sptr"
; Flags : REGISTER_NOTIFICATION_FLAGS -> "int"
; HDEVNOTIFY RegisterDeviceNotificationW(HANDLE hRecipient, void* NotificationFilter, REGISTER_NOTIFICATION_FLAGS Flags)
#uselib "USER32.dll"
#cfunc global RegisterDeviceNotificationW "RegisterDeviceNotificationW" intptr, intptr, int
; res = RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags)
; hRecipient : HANDLE -> "intptr"
; NotificationFilter : void* -> "intptr"
; Flags : REGISTER_NOTIFICATION_FLAGS -> "int"
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	user32 = windows.NewLazySystemDLL("USER32.dll")
	procRegisterDeviceNotificationW = user32.NewProc("RegisterDeviceNotificationW")
)

// hRecipient (HANDLE), NotificationFilter (void*), Flags (REGISTER_NOTIFICATION_FLAGS)
r1, _, err := procRegisterDeviceNotificationW.Call(
	uintptr(hRecipient),
	uintptr(NotificationFilter),
	uintptr(Flags),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // HDEVNOTIFY
function RegisterDeviceNotificationW(
  hRecipient: THandle;   // HANDLE
  NotificationFilter: Pointer;   // void*
  Flags: DWORD   // REGISTER_NOTIFICATION_FLAGS
): THandle; stdcall;
  external 'USER32.dll' name 'RegisterDeviceNotificationW';
result := DllCall("USER32\RegisterDeviceNotificationW"
    , "Ptr", hRecipient   ; HANDLE
    , "Ptr", NotificationFilter   ; void*
    , "UInt", Flags   ; REGISTER_NOTIFICATION_FLAGS
    , "Ptr")   ; return: HDEVNOTIFY
●RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags) = DLL("USER32.dll", "void* RegisterDeviceNotificationW(void*, void*, dword)")
# 呼び出し: RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags)
# hRecipient : HANDLE -> "void*"
# NotificationFilter : void* -> "void*"
# Flags : REGISTER_NOTIFICATION_FLAGS -> "dword"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
# ※-W(Unicode)関数。なでしこ1はANSIのため -A 版の利用を推奨。
const std = @import("std");

extern "user32" fn RegisterDeviceNotificationW(
    hRecipient: ?*anyopaque, // HANDLE
    NotificationFilter: ?*anyopaque, // void*
    Flags: u32 // REGISTER_NOTIFICATION_FLAGS
) callconv(std.os.windows.WINAPI) ?*anyopaque;
// Unicode(-W): UTF-16LE のヌル終端バッファ([*c]const u16)を渡す。
proc RegisterDeviceNotificationW(
    hRecipient: pointer,  # HANDLE
    NotificationFilter: pointer,  # void*
    Flags: uint32  # REGISTER_NOTIFICATION_FLAGS
): pointer {.importc: "RegisterDeviceNotificationW", stdcall, dynlib: "USER32.dll".}
# Unicode(-W): WideCString は newWideCString("...") で生成。
pragma(lib, "user32");
extern(Windows)
void* RegisterDeviceNotificationW(
    void* hRecipient,   // HANDLE
    void* NotificationFilter,   // void*
    uint Flags   // REGISTER_NOTIFICATION_FLAGS
);
ccall((:RegisterDeviceNotificationW, "USER32.dll"), stdcall, Ptr{Cvoid},
      (Ptr{Cvoid}, Ptr{Cvoid}, UInt32),
      hRecipient, NotificationFilter, Flags)
# hRecipient : HANDLE -> Ptr{Cvoid}
# NotificationFilter : void* -> Ptr{Cvoid}
# Flags : REGISTER_NOTIFICATION_FLAGS -> UInt32
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
# Unicode(-W): Cwstring には transcode(UInt16, "...") 等で UTF-16 を渡す。
local ffi = require("ffi")
ffi.cdef[[
void* RegisterDeviceNotificationW(
    void* hRecipient,
    void* NotificationFilter,
    uint32_t Flags);
]]
local user32 = ffi.load("user32")
-- user32.RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags)
-- hRecipient : HANDLE
-- NotificationFilter : void*
-- Flags : REGISTER_NOTIFICATION_FLAGS
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
-- Unicode(-W): uint16_t* には UTF-16LE のバッファ(ffi.new("uint16_t[?]", ...))を渡す。
const koffi = require('koffi');
const lib = koffi.load('USER32.dll');
const RegisterDeviceNotificationW = lib.func('__stdcall', 'RegisterDeviceNotificationW', 'void *', ['void *', 'void *', 'uint32_t']);
// RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags)
// hRecipient : HANDLE -> 'void *'
// NotificationFilter : void* -> 'void *'
// Flags : REGISTER_NOTIFICATION_FLAGS -> 'uint32_t'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("USER32.dll", {
  RegisterDeviceNotificationW: { parameters: ["pointer", "pointer", "u32"], result: "pointer" },
});
// lib.symbols.RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags)
// hRecipient : HANDLE -> "pointer"
// NotificationFilter : void* -> "pointer"
// Flags : REGISTER_NOTIFICATION_FLAGS -> "u32"
// 文字列は "buffer"。Unicode(-W) は new TextEncoder() ではなく UTF-16LE のバイト列(末尾に \x00\x00)を Uint8Array で渡す。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
void* RegisterDeviceNotificationW(
    void* hRecipient,
    void* NotificationFilter,
    uint32_t Flags);
C, "USER32.dll");
// $ffi->RegisterDeviceNotificationW(hRecipient, NotificationFilter, Flags);
// hRecipient : HANDLE
// NotificationFilter : void*
// Flags : REGISTER_NOTIFICATION_FLAGS
// 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
// WINAPI(stdcall): x64 では呼出規約が統一されるため問題なし。x86 では __stdcall 対応のラッパが必要な場合あり。
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;

public interface User32 extends StdCallLibrary {
    User32 INSTANCE = Native.load("user32", User32.class, W32APIOptions.UNICODE_OPTIONS);
    Pointer RegisterDeviceNotificationW(
        Pointer hRecipient,   // HANDLE
        Pointer NotificationFilter,   // void*
        int Flags   // REGISTER_NOTIFICATION_FLAGS
    );
}
// Unicode(-W): WString(入力)/char[](出力)で UTF-16 をマーシャリング。
@[Link("user32")]
lib LibUSER32
  fun RegisterDeviceNotificationW = RegisterDeviceNotificationW(
    hRecipient : Void*,   # HANDLE
    NotificationFilter : Void*,   # void*
    Flags : UInt32   # REGISTER_NOTIFICATION_FLAGS
  ) : Void*
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef RegisterDeviceNotificationWNative = Pointer<Void> Function(Pointer<Void>, Pointer<Void>, Uint32);
typedef RegisterDeviceNotificationWDart = Pointer<Void> Function(Pointer<Void>, Pointer<Void>, int);
final RegisterDeviceNotificationW = DynamicLibrary.open('USER32.dll')
    .lookupFunction<RegisterDeviceNotificationWNative, RegisterDeviceNotificationWDart>('RegisterDeviceNotificationW');
// hRecipient : HANDLE -> Pointer<Void>
// NotificationFilter : void* -> Pointer<Void>
// Flags : REGISTER_NOTIFICATION_FLAGS -> Uint32
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function RegisterDeviceNotificationW(
  hRecipient: THandle;   // HANDLE
  NotificationFilter: Pointer;   // void*
  Flags: DWORD   // REGISTER_NOTIFICATION_FLAGS
): THandle; stdcall;
  external 'USER32.dll' name 'RegisterDeviceNotificationW';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "RegisterDeviceNotificationW"
  c_RegisterDeviceNotificationW :: Ptr () -> Ptr () -> Word32 -> IO (Ptr ())
-- hRecipient : HANDLE -> Ptr ()
-- NotificationFilter : void* -> Ptr ()
-- Flags : REGISTER_NOTIFICATION_FLAGS -> Word32
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let registerdevicenotificationw =
  foreign "RegisterDeviceNotificationW"
    ((ptr void) @-> (ptr void) @-> uint32_t @-> returning (ptr void))
(* hRecipient : HANDLE -> (ptr void) *)
(* NotificationFilter : void* -> (ptr void) *)
(* Flags : REGISTER_NOTIFICATION_FLAGS -> uint32_t *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library user32 (t "USER32.dll"))
(cffi:use-foreign-library user32)

(cffi:defcfun ("RegisterDeviceNotificationW" register-device-notification-w :convention :stdcall) :pointer
  (h-recipient :pointer)   ; HANDLE
  (notification-filter :pointer)   ; void*
  (flags :uint32))   ; REGISTER_NOTIFICATION_FLAGS
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $RegisterDeviceNotificationW = Win32::API::More->new('USER32',
    'HANDLE RegisterDeviceNotificationW(HANDLE hRecipient, LPVOID NotificationFilter, DWORD Flags)');
# my $ret = $RegisterDeviceNotificationW->Call($hRecipient, $NotificationFilter, $Flags);
# hRecipient : HANDLE -> HANDLE
# NotificationFilter : void* -> LPVOID
# Flags : REGISTER_NOTIFICATION_FLAGS -> DWORD
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。
# Unicode(-W): LPCWSTR/LPWSTR は Win32::API が UTF-16 変換を行う。

関連項目

文字セット違い
公式の関連項目
使用する型