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

SetTimer

関数
指定間隔で発火するタイマーを作成する。
DLLUSER32.dll呼出規約winapiSetLastErrorあり対応OSWindows 2000 以降

シグネチャ

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

UINT_PTR SetTimer(
    HWND hWnd,   // optional
    UINT_PTR nIDEvent,
    DWORD uElapse,
    TIMERPROC lpTimerFunc   // optional
);

パラメーター

名前方向説明
hWndHWNDinoptionalタイマーに関連付けるウィンドウへのハンドル。このウィンドウは呼び出し元のスレッドが所有している必要があります。hWndNULL 値を渡し、かつ既存タイマーの nIDEvent を渡した場合、そのタイマーは、既存の非 NULL の hWnd タイマーが置き換えられるのと同じように置き換えられます。
nIDEventUINT_PTRin0 以外のタイマー識別子。hWnd パラメーターが NULL で、nIDEvent が既存のタイマーと一致しない場合、nIDEvent は無視され、新しいタイマー ID が生成されます。hWnd パラメーターが NULL でなく、hWnd で指定されたウィンドウに nIDEvent の値を持つタイマーが既に存在する場合、その既存タイマーは新しいタイマーに置き換えられます。SetTimer がタイマーを置き換えると、タイマーはリセットされます。したがって、現在のタイムアウト値が経過した後にメッセージが送信され、以前に設定したタイムアウト値は無視されます。既存タイマーを置き換える意図がない呼び出しでは、hWndNULL の場合、nIDEvent は 0 にする必要があります。
uElapseDWORDin

タイムアウト値(ミリ秒単位)。

uElapseUSER_TIMER_MINIMUM (0x0000000A) より小さい場合、タイムアウトは USER_TIMER_MINIMUM に設定されます。uElapseUSER_TIMER_MAXIMUM (0x7FFFFFFF) より大きい場合、タイムアウトは USER_TIMER_MAXIMUM に設定されます。

lpTimerFuncTIMERPROCinoptionalタイムアウト値が経過したときに通知される関数へのポインター。この関数の詳細については、TimerProc を参照してください。lpTimerFuncNULL の場合、システムはアプリケーションのキューに WM_TIMER メッセージをポストします。メッセージの MSG 構造体の hwnd メンバーには、hWnd パラメーターの値が格納されます。

戻り値の型: UINT_PTR

公式ドキュメント

指定したタイムアウト値でタイマーを作成します。

戻り値

型: UINT_PTR

関数が成功し、かつ hWnd パラメーターが NULL の場合、戻り値は新しいタイマーを識別する整数です。アプリケーションはこの値を KillTimer 関数に渡してタイマーを破棄できます。

関数が成功し、かつ hWnd パラメーターが NULL でない場合、戻り値は 0 以外の整数です。アプリケーションは nIDEvent パラメーターの値を KillTimer 関数に渡してタイマーを破棄できます。

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

解説(Remarks)

アプリケーションは、ウィンドウプロシージャに WM_TIMER の case 文を含めるか、タイマー作成時に TimerProc コールバック関数を指定することで、WM_TIMER メッセージを処理できます。TimerProc コールバック関数を指定した場合、DispatchMessage は lParam が NULL でない WM_TIMER を処理する際に、ウィンドウプロシージャを呼び出す代わりにそのコールバック関数を呼び出します。したがって、WM_TIMER を処理する代わりに TimerProc を使用する場合でも、呼び出し元のスレッドでメッセージをディスパッチする必要があります。

WM_TIMER メッセージの wParam パラメーターには、nIDEvent パラメーターの値が格納されます。

タイマー識別子 nIDEvent は、関連付けられたウィンドウに固有です。別のウィンドウは、他のウィンドウが所有するタイマーと同じ識別子を持つ独自のタイマーを持つことができます。これらのタイマーは別個のものです。

hWndNULL の場合、SetTimer はタイマー ID を再利用できます。

SetTimer やその他のタイマー関連関数を使用する前に、SetUserObjectInformationW 関数を通じて UOI_TIMERPROC_EXCEPTION_SUPPRESSION フラグを false に設定することをお勧めします。設定しないと、アプリケーションが予測不能な動作をし、セキュリティ上の脆弱性を突かれる可能性があります。詳細については、SetUserObjectInformationW を参照してください。

例については、タイマーの作成を参照してください。

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

各言語での呼び出し定義

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

UINT_PTR SetTimer(
    HWND hWnd,   // optional
    UINT_PTR nIDEvent,
    DWORD uElapse,
    TIMERPROC lpTimerFunc   // optional
);
[DllImport("USER32.dll", SetLastError = true, ExactSpelling = true)]
static extern UIntPtr SetTimer(
    IntPtr hWnd,   // HWND optional
    UIntPtr nIDEvent,   // UINT_PTR
    uint uElapse,   // DWORD
    IntPtr lpTimerFunc   // TIMERPROC optional
);
<DllImport("USER32.dll", SetLastError:=True, ExactSpelling:=True)>
Public Shared Function SetTimer(
    hWnd As IntPtr,   ' HWND optional
    nIDEvent As UIntPtr,   ' UINT_PTR
    uElapse As UInteger,   ' DWORD
    lpTimerFunc As IntPtr   ' TIMERPROC optional
) As UIntPtr
End Function
' hWnd : HWND optional
' nIDEvent : UINT_PTR
' uElapse : DWORD
' lpTimerFunc : TIMERPROC optional
Declare PtrSafe Function SetTimer Lib "user32" ( _
    ByVal hWnd As LongPtr, _
    ByVal nIDEvent As LongPtr, _
    ByVal uElapse As Long, _
    ByVal lpTimerFunc As LongPtr) As LongPtr
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

SetTimer = ctypes.windll.user32.SetTimer
SetTimer.restype = ctypes.c_size_t
SetTimer.argtypes = [
    wintypes.HANDLE,  # hWnd : HWND optional
    ctypes.c_size_t,  # nIDEvent : UINT_PTR
    wintypes.DWORD,  # uElapse : DWORD
    ctypes.c_void_p,  # lpTimerFunc : TIMERPROC optional
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('USER32.dll')
SetTimer = Fiddle::Function.new(
  lib['SetTimer'],
  [
    Fiddle::TYPE_VOIDP,  # hWnd : HWND optional
    Fiddle::TYPE_UINTPTR_T,  # nIDEvent : UINT_PTR
    -Fiddle::TYPE_INT,  # uElapse : DWORD
    Fiddle::TYPE_VOIDP,  # lpTimerFunc : TIMERPROC optional
  ],
  Fiddle::TYPE_UINTPTR_T)
#[link(name = "user32")]
extern "system" {
    fn SetTimer(
        hWnd: *mut core::ffi::c_void,  // HWND optional
        nIDEvent: usize,  // UINT_PTR
        uElapse: u32,  // DWORD
        lpTimerFunc: *const core::ffi::c_void  // TIMERPROC optional
    ) -> usize;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[DllImport("USER32.dll", SetLastError = true)]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, IntPtr lpTimerFunc);
"@
$api = Add-Type -MemberDefinition $sig -Name 'USER32_SetTimer' -Namespace Win32 -PassThru
# $api::SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc)
#uselib "USER32.dll"
#func global SetTimer "SetTimer" sptr, sptr, sptr, sptr
; SetTimer hWnd, nIDEvent, uElapse, lpTimerFunc   ; 戻り値は stat
; hWnd : HWND optional -> "sptr"
; nIDEvent : UINT_PTR -> "sptr"
; uElapse : DWORD -> "sptr"
; lpTimerFunc : TIMERPROC optional -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
#uselib "USER32.dll"
#cfunc global SetTimer "SetTimer" sptr, sptr, int, sptr
; res = SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc)
; hWnd : HWND optional -> "sptr"
; nIDEvent : UINT_PTR -> "sptr"
; uElapse : DWORD -> "int"
; lpTimerFunc : TIMERPROC optional -> "sptr"
; UINT_PTR SetTimer(HWND hWnd, UINT_PTR nIDEvent, DWORD uElapse, TIMERPROC lpTimerFunc)
#uselib "USER32.dll"
#cfunc global SetTimer "SetTimer" intptr, intptr, int, intptr
; res = SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc)
; hWnd : HWND optional -> "intptr"
; nIDEvent : UINT_PTR -> "intptr"
; uElapse : DWORD -> "int"
; lpTimerFunc : TIMERPROC optional -> "intptr"
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	user32 = windows.NewLazySystemDLL("USER32.dll")
	procSetTimer = user32.NewProc("SetTimer")
)

// hWnd (HWND optional), nIDEvent (UINT_PTR), uElapse (DWORD), lpTimerFunc (TIMERPROC optional)
r1, _, err := procSetTimer.Call(
	uintptr(hWnd),
	uintptr(nIDEvent),
	uintptr(uElapse),
	uintptr(lpTimerFunc),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // UINT_PTR
function SetTimer(
  hWnd: THandle;   // HWND optional
  nIDEvent: NativeUInt;   // UINT_PTR
  uElapse: DWORD;   // DWORD
  lpTimerFunc: Pointer   // TIMERPROC optional
): NativeUInt; stdcall;
  external 'USER32.dll' name 'SetTimer';
result := DllCall("USER32\SetTimer"
    , "Ptr", hWnd   ; HWND optional
    , "UPtr", nIDEvent   ; UINT_PTR
    , "UInt", uElapse   ; DWORD
    , "Ptr", lpTimerFunc   ; TIMERPROC optional
    , "UPtr")   ; return: UINT_PTR
●SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc) = DLL("USER32.dll", "int SetTimer(void*, int, dword, void*)")
# 呼び出し: SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc)
# hWnd : HWND optional -> "void*"
# nIDEvent : UINT_PTR -> "int"
# uElapse : DWORD -> "dword"
# lpTimerFunc : TIMERPROC optional -> "void*"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
const std = @import("std");

extern "user32" fn SetTimer(
    hWnd: ?*anyopaque, // HWND optional
    nIDEvent: usize, // UINT_PTR
    uElapse: u32, // DWORD
    lpTimerFunc: ?*anyopaque // TIMERPROC optional
) callconv(std.os.windows.WINAPI) usize;
proc SetTimer(
    hWnd: pointer,  # HWND optional
    nIDEvent: uint,  # UINT_PTR
    uElapse: uint32,  # DWORD
    lpTimerFunc: pointer  # TIMERPROC optional
): uint {.importc: "SetTimer", stdcall, dynlib: "USER32.dll".}
pragma(lib, "user32");
extern(Windows)
size_t SetTimer(
    void* hWnd,   // HWND optional
    size_t nIDEvent,   // UINT_PTR
    uint uElapse,   // DWORD
    void* lpTimerFunc   // TIMERPROC optional
);
ccall((:SetTimer, "USER32.dll"), stdcall, Csize_t,
      (Ptr{Cvoid}, Csize_t, UInt32, Ptr{Cvoid}),
      hWnd, nIDEvent, uElapse, lpTimerFunc)
# hWnd : HWND optional -> Ptr{Cvoid}
# nIDEvent : UINT_PTR -> Csize_t
# uElapse : DWORD -> UInt32
# lpTimerFunc : TIMERPROC optional -> Ptr{Cvoid}
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
local ffi = require("ffi")
ffi.cdef[[
uintptr_t SetTimer(
    void* hWnd,
    uintptr_t nIDEvent,
    uint32_t uElapse,
    void* lpTimerFunc);
]]
local user32 = ffi.load("user32")
-- user32.SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc)
-- hWnd : HWND optional
-- nIDEvent : UINT_PTR
-- uElapse : DWORD
-- lpTimerFunc : TIMERPROC optional
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
const koffi = require('koffi');
const lib = koffi.load('USER32.dll');
const SetTimer = lib.func('__stdcall', 'SetTimer', 'uintptr_t', ['void *', 'uintptr_t', 'uint32_t', 'void *']);
// SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc)
// hWnd : HWND optional -> 'void *'
// nIDEvent : UINT_PTR -> 'uintptr_t'
// uElapse : DWORD -> 'uint32_t'
// lpTimerFunc : TIMERPROC optional -> 'void *'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
// コールバック(関数ポインタ)は koffi.proto/koffi.register で型を定義して渡す(素の void* では JS 関数を渡せない)。
const lib = Deno.dlopen("USER32.dll", {
  SetTimer: { parameters: ["pointer", "usize", "u32", "pointer"], result: "usize" },
});
// lib.symbols.SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc)
// hWnd : HWND optional -> "pointer"
// nIDEvent : UINT_PTR -> "usize"
// uElapse : DWORD -> "u32"
// lpTimerFunc : TIMERPROC optional -> "pointer"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
size_t SetTimer(
    void* hWnd,
    size_t nIDEvent,
    uint32_t uElapse,
    void* lpTimerFunc);
C, "USER32.dll");
// $ffi->SetTimer(hWnd, nIDEvent, uElapse, lpTimerFunc);
// hWnd : HWND optional
// nIDEvent : UINT_PTR
// uElapse : DWORD
// lpTimerFunc : TIMERPROC optional
// 構造体/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);
    long SetTimer(
        Pointer hWnd,   // HWND optional
        long nIDEvent,   // UINT_PTR
        int uElapse,   // DWORD
        Callback lpTimerFunc   // TIMERPROC optional
    );
}
@[Link("user32")]
lib LibUSER32
  fun SetTimer = SetTimer(
    hWnd : Void*,   # HWND optional
    nIDEvent : LibC::SizeT,   # UINT_PTR
    uElapse : UInt32,   # DWORD
    lpTimerFunc : Void*   # TIMERPROC optional
  ) : LibC::SizeT
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef SetTimerNative = UintPtr Function(Pointer<Void>, UintPtr, Uint32, Pointer<Void>);
typedef SetTimerDart = int Function(Pointer<Void>, int, int, Pointer<Void>);
final SetTimer = DynamicLibrary.open('USER32.dll')
    .lookupFunction<SetTimerNative, SetTimerDart>('SetTimer');
// hWnd : HWND optional -> Pointer<Void>
// nIDEvent : UINT_PTR -> UintPtr
// uElapse : DWORD -> Uint32
// lpTimerFunc : TIMERPROC optional -> Pointer<Void>
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function SetTimer(
  hWnd: THandle;   // HWND optional
  nIDEvent: NativeUInt;   // UINT_PTR
  uElapse: DWORD;   // DWORD
  lpTimerFunc: Pointer   // TIMERPROC optional
): NativeUInt; stdcall;
  external 'USER32.dll' name 'SetTimer';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "SetTimer"
  c_SetTimer :: Ptr () -> CUIntPtr -> Word32 -> Ptr () -> IO CUIntPtr
-- hWnd : HWND optional -> Ptr ()
-- nIDEvent : UINT_PTR -> CUIntPtr
-- uElapse : DWORD -> Word32
-- lpTimerFunc : TIMERPROC optional -> Ptr ()
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let settimer =
  foreign "SetTimer"
    ((ptr void) @-> size_t @-> uint32_t @-> (ptr void) @-> returning size_t)
(* hWnd : HWND optional -> (ptr void) *)
(* nIDEvent : UINT_PTR -> size_t *)
(* uElapse : DWORD -> uint32_t *)
(* lpTimerFunc : TIMERPROC optional -> (ptr void) *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library user32 (t "USER32.dll"))
(cffi:use-foreign-library user32)

(cffi:defcfun ("SetTimer" set-timer :convention :stdcall) :uint64
  (h-wnd :pointer)   ; HWND optional
  (n-idevent :uint64)   ; UINT_PTR
  (u-elapse :uint32)   ; DWORD
  (lp-timer-func :pointer))   ; TIMERPROC optional
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $SetTimer = Win32::API::More->new('USER32',
    'WPARAM SetTimer(HANDLE hWnd, WPARAM nIDEvent, DWORD uElapse, LPVOID lpTimerFunc)');
# my $ret = $SetTimer->Call($hWnd, $nIDEvent, $uElapse, $lpTimerFunc);
# hWnd : HWND optional -> HANDLE
# nIDEvent : UINT_PTR -> WPARAM
# uElapse : DWORD -> DWORD
# lpTimerFunc : TIMERPROC optional -> LPVOID
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。
# コールバック(関数ポインタ)は Perl sub を直接渡せません。Win32::API::Callback を使用してください。

関連項目

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