Win32 API 日本語リファレンス
ホームDevices.DeviceAndDriverInstallation › CM_Unregister_Notification

CM_Unregister_Notification

関数
デバイス変更通知の登録を解除する。
DLLCFGMGR32.dll呼出規約winapi対応OSwindows8.0

シグネチャ

// CFGMGR32.dll
#include <windows.h>

CONFIGRET CM_Unregister_Notification(
    HCMNOTIFICATION NotifyContext
);

パラメーター

名前方向説明
NotifyContextHCMNOTIFICATIONinCM_Register_Notification 関数から返された HCMNOTIFICATION ハンドル。

戻り値の型: CONFIGRET

公式ドキュメント

コードが Windows 7 以前のバージョンの Windows を対象とする場合は、CM_Unregister_Notification ではなく UnregisterDeviceNotification を使用してください。

戻り値

操作が成功した場合、この関数は CR_SUCCESS を返します。それ以外の場合は、Cfgmgr32.h で定義されている CR_ プレフィックス付きのエラーコードのいずれかを返します。

解説(Remarks)

通知コールバックから CM_Unregister_Notification を呼び出さないでください。CM_Unregister_Notification は保留中のコールバックが完了するまで待機するため、デッドロックが発生する可能性があります。

通知コールバックから登録を解除したい場合は、代わりに非同期で行う必要があります。 次の手順は、その一例です。

  1. 通知で使用するコンテキスト構造体を割り当てます。 スレッドプール作業構造体 (PTP_WORK) へのポインターと、通知コールバックに渡したいその他の情報を含めます。
  2. CreateThreadpoolWork を呼び出します。 CM_Unregister_Notification を呼び出すコールバック関数を指定します。 返された作業構造体を、先に割り当てたコンテキスト構造体に追加します。
  3. CM_Register_Notification を呼び出し、pContext パラメーターとしてコンテキスト構造体を渡します。
  4. 処理を行い、通知を受け取るなどします。
  5. 通知コールバックの中から SubmitThreadpoolWork を呼び出し、コンテキスト構造体に格納したスレッドプール作業構造体 (PTP_WORK) へのポインターを渡します。
  6. スレッドプールのスレッドが実行されると、作業項目が CM_Unregister_Notification を呼び出します。
  7. CloseThreadpoolWork を呼び出して作業オブジェクトを解放します。
コンテキスト構造体の使用が終わったら、リソースを解放して構造体を解放することを忘れないでください。
注意 作業項目が CM_Unregister_Notification を呼び出すまで、コンテキスト構造体を解放しないでください。 スレッドプール作業項目を送信してから、その作業項目が CM_Unregister_Notification を呼び出すまでの間も、通知を受け取る可能性があります。

次の例は、「解説」セクションで説明したとおりに、通知コールバックから登録を解除する方法を示しています。

typedef struct _CALLBACK_CONTEXT {
    BOOL bUnregister;
    PTP_WORK pWork;
    HCMNOTIFICATION hNotify;
    CRITICAL_SECTION lock;
} CALLBACK_CONTEXT, *PCALLBACK_CONTEXT;

DWORD
WINAPI
EventCallback(
    __in HCMNOTIFICATION hNotification,
    __in PVOID Context,
    __in CM_NOTIFY_ACTION Action,
    __in PCM_NOTIFY_EVENT_DATA EventData,
    __in DWORD EventDataSize
    )
{
    PCALLBACK_CONTEXT pCallbackContext = (PCALLBACK_CONTEXT)Context;

   // コールバックから登録を解除する
    EnterCriticalSection(&(pCallbackContext->lock));

    // 登録呼び出しが戻る前にこのコールバックが呼ばれた場合に備えて、通知ハンドルが確実に設定されるようにする
    Context->hNotify = hNotification;

    if (!pCallbackContext->bUnregister) {
        pCallbackContext->bUnregister = TRUE;
        SubmitThreadpoolWork(pCallbackContext->pWork);
    }

    LeaveCriticalSection(&(pCallbackContext->lock));

    return ERROR_SUCCESS;
};

VOID
CALLBACK
WorkCallback(
    _Inout_ PTP_CALLBACK_INSTANCE Instance,
    _Inout_opt_ PVOID Context,
    _Inout_ PTP_WORK pWork
    )
{
    PCALLBACK_CONTEXT pCallbackContext = (PCALLBACK_CONTEXT)Context;

    CM_Unregister_Notification(pCallbackContext->hNotify);
}

VOID NotificationFunction()
{
    CONFIGRET cr = CR_SUCCESS;
    HRESULT hr = S_OK;
    CM_NOTIFY_FILTER NotifyFilter = { 0 };
    BOOL bShouldUnregister = FALSE;
    PCALLBACK_CONTEXT context;

    context = (PCALLBACK_CONTEXT)HeapAlloc(GetProcessHeap(),
                                           HEAP_ZERO_MEMORY,
                                           sizeof(CALLBACK_CONTEXT));
    if (context == NULL) {
        goto end;
    }

    InitializeCriticalSection(&(context->lock));

    NotifyFilter.cbSize = sizeof(NotifyFilter);
    NotifyFilter.Flags = 0;
    NotifyFilter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINSTANCE;
    NotifyFilter.Reserved = 0;

    hr = StringCchCopy(NotifyFilter.u.DeviceInstance.InstanceId,
                       MAX_DEVICE_ID_LEN,
                       TEST_DEVICE_INSTANCE_ID);
    if (FAILED(hr)) {
        goto end;
    }

    context->pWork = CreateThreadpoolWork(WorkCallback, context, NULL);
    if (context->pWork == NULL) {
        goto end;
    }

    cr = CM_Register_Notification(&NotifyFilter,
                                  context,
                                  EventCallback,
                                  &context->hNotify);
   if (cr != CR_SUCCESS) {
        goto end;
    }

    // ... ここで処理を行う ...

    EnterCriticalSection(&(context->lock));

    if (!context->bUnregister) {
        // コールバック以外から登録を解除する
        bShouldUnregister = TRUE;
        context->bUnregister = TRUE;
    }

    LeaveCriticalSection(&(context->lock));

    if (bShouldUnregister) {
        cr = CM_Unregister_Notification(context->hNotify);
        if (cr != CR_SUCCESS) {
            goto end;
        }
    } else {
        // 登録解除をコールバックが行う場合は、スレッドプール作業項目が登録解除を完了するまで待機する
        WaitForThreadpoolWorkCallbacks(context->pWork, FALSE);
    }

end:

    if (context != NULL) {
        if (context->pWork != NULL) {
            CloseThreadpoolWork(context->pWork);
        }

        DeleteCriticalSection(&(context->lock));

        HeapFree(GetProcessHeap(), 0, context);
    }

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

各言語での呼び出し定義

// CFGMGR32.dll
#include <windows.h>

CONFIGRET CM_Unregister_Notification(
    HCMNOTIFICATION NotifyContext
);
[DllImport("CFGMGR32.dll", ExactSpelling = true)]
static extern uint CM_Unregister_Notification(
    IntPtr NotifyContext   // HCMNOTIFICATION
);
<DllImport("CFGMGR32.dll", ExactSpelling:=True)>
Public Shared Function CM_Unregister_Notification(
    NotifyContext As IntPtr   ' HCMNOTIFICATION
) As UInteger
End Function
' NotifyContext : HCMNOTIFICATION
Declare PtrSafe Function CM_Unregister_Notification Lib "cfgmgr32" ( _
    ByVal NotifyContext As LongPtr) As Long
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

CM_Unregister_Notification = ctypes.windll.cfgmgr32.CM_Unregister_Notification
CM_Unregister_Notification.restype = wintypes.DWORD
CM_Unregister_Notification.argtypes = [
    wintypes.HANDLE,  # NotifyContext : HCMNOTIFICATION
]
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('CFGMGR32.dll')
CM_Unregister_Notification = Fiddle::Function.new(
  lib['CM_Unregister_Notification'],
  [
    Fiddle::TYPE_VOIDP,  # NotifyContext : HCMNOTIFICATION
  ],
  -Fiddle::TYPE_INT)
#[link(name = "cfgmgr32")]
extern "system" {
    fn CM_Unregister_Notification(
        NotifyContext: *mut core::ffi::c_void  // HCMNOTIFICATION
    ) -> u32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[DllImport("CFGMGR32.dll")]
public static extern uint CM_Unregister_Notification(IntPtr NotifyContext);
"@
$api = Add-Type -MemberDefinition $sig -Name 'CFGMGR32_CM_Unregister_Notification' -Namespace Win32 -PassThru
# $api::CM_Unregister_Notification(NotifyContext)
#uselib "CFGMGR32.dll"
#func global CM_Unregister_Notification "CM_Unregister_Notification" sptr
; CM_Unregister_Notification NotifyContext   ; 戻り値は stat
; NotifyContext : HCMNOTIFICATION -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
#uselib "CFGMGR32.dll"
#cfunc global CM_Unregister_Notification "CM_Unregister_Notification" sptr
; res = CM_Unregister_Notification(NotifyContext)
; NotifyContext : HCMNOTIFICATION -> "sptr"
; CONFIGRET CM_Unregister_Notification(HCMNOTIFICATION NotifyContext)
#uselib "CFGMGR32.dll"
#cfunc global CM_Unregister_Notification "CM_Unregister_Notification" intptr
; res = CM_Unregister_Notification(NotifyContext)
; NotifyContext : HCMNOTIFICATION -> "intptr"
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	cfgmgr32 = windows.NewLazySystemDLL("CFGMGR32.dll")
	procCM_Unregister_Notification = cfgmgr32.NewProc("CM_Unregister_Notification")
)

// NotifyContext (HCMNOTIFICATION)
r1, _, err := procCM_Unregister_Notification.Call(
	uintptr(NotifyContext),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // CONFIGRET
function CM_Unregister_Notification(
  NotifyContext: THandle   // HCMNOTIFICATION
): DWORD; stdcall;
  external 'CFGMGR32.dll' name 'CM_Unregister_Notification';
result := DllCall("CFGMGR32\CM_Unregister_Notification"
    , "Ptr", NotifyContext   ; HCMNOTIFICATION
    , "UInt")   ; return: CONFIGRET
●CM_Unregister_Notification(NotifyContext) = DLL("CFGMGR32.dll", "dword CM_Unregister_Notification(void*)")
# 呼び出し: CM_Unregister_Notification(NotifyContext)
# NotifyContext : HCMNOTIFICATION -> "void*"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
const std = @import("std");

extern "cfgmgr32" fn CM_Unregister_Notification(
    NotifyContext: ?*anyopaque // HCMNOTIFICATION
) callconv(std.os.windows.WINAPI) u32;
proc CM_Unregister_Notification(
    NotifyContext: pointer  # HCMNOTIFICATION
): uint32 {.importc: "CM_Unregister_Notification", stdcall, dynlib: "CFGMGR32.dll".}
pragma(lib, "cfgmgr32");
extern(Windows)
uint CM_Unregister_Notification(
    void* NotifyContext   // HCMNOTIFICATION
);
ccall((:CM_Unregister_Notification, "CFGMGR32.dll"), stdcall, UInt32,
      (Ptr{Cvoid},),
      NotifyContext)
# NotifyContext : HCMNOTIFICATION -> Ptr{Cvoid}
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
local ffi = require("ffi")
ffi.cdef[[
uint32_t CM_Unregister_Notification(
    void* NotifyContext);
]]
local cfgmgr32 = ffi.load("cfgmgr32")
-- cfgmgr32.CM_Unregister_Notification(NotifyContext)
-- NotifyContext : HCMNOTIFICATION
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
const koffi = require('koffi');
const lib = koffi.load('CFGMGR32.dll');
const CM_Unregister_Notification = lib.func('__stdcall', 'CM_Unregister_Notification', 'uint32_t', ['void *']);
// CM_Unregister_Notification(NotifyContext)
// NotifyContext : HCMNOTIFICATION -> 'void *'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("CFGMGR32.dll", {
  CM_Unregister_Notification: { parameters: ["pointer"], result: "u32" },
});
// lib.symbols.CM_Unregister_Notification(NotifyContext)
// NotifyContext : HCMNOTIFICATION -> "pointer"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
uint32_t CM_Unregister_Notification(
    void* NotifyContext);
C, "CFGMGR32.dll");
// $ffi->CM_Unregister_Notification(NotifyContext);
// NotifyContext : HCMNOTIFICATION
// 構造体/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 Cfgmgr32 extends StdCallLibrary {
    Cfgmgr32 INSTANCE = Native.load("cfgmgr32", Cfgmgr32.class);
    int CM_Unregister_Notification(
        Pointer NotifyContext   // HCMNOTIFICATION
    );
}
@[Link("cfgmgr32")]
lib LibCFGMGR32
  fun CM_Unregister_Notification = CM_Unregister_Notification(
    NotifyContext : Void*   # HCMNOTIFICATION
  ) : UInt32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef CM_Unregister_NotificationNative = Uint32 Function(Pointer<Void>);
typedef CM_Unregister_NotificationDart = int Function(Pointer<Void>);
final CM_Unregister_Notification = DynamicLibrary.open('CFGMGR32.dll')
    .lookupFunction<CM_Unregister_NotificationNative, CM_Unregister_NotificationDart>('CM_Unregister_Notification');
// NotifyContext : HCMNOTIFICATION -> Pointer<Void>
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function CM_Unregister_Notification(
  NotifyContext: THandle   // HCMNOTIFICATION
): DWORD; stdcall;
  external 'CFGMGR32.dll' name 'CM_Unregister_Notification';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "CM_Unregister_Notification"
  c_CM_Unregister_Notification :: Ptr () -> IO Word32
-- NotifyContext : HCMNOTIFICATION -> Ptr ()
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let cm_unregister_notification =
  foreign "CM_Unregister_Notification"
    ((ptr void) @-> returning uint32_t)
(* NotifyContext : HCMNOTIFICATION -> (ptr void) *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library cfgmgr32 (t "CFGMGR32.dll"))
(cffi:use-foreign-library cfgmgr32)

(cffi:defcfun ("CM_Unregister_Notification" cm-unregister-notification :convention :stdcall) :uint32
  (notify-context :pointer))   ; HCMNOTIFICATION
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $CM_Unregister_Notification = Win32::API::More->new('CFGMGR32',
    'DWORD CM_Unregister_Notification(HANDLE NotifyContext)');
# my $ret = $CM_Unregister_Notification->Call($NotifyContext);
# NotifyContext : HCMNOTIFICATION -> HANDLE
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。

関連項目

公式の関連項目
使用する型