Skip to content
2011.02.05 22:09


조회 수 18700 추천 수 0 댓글 0


Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄


Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄


Specifies a function to call automatically when the script receives the specified message.

지정된 메시지를 받을때 자동으로 호출되는 명령어.

OnMessage(MsgNumber [, "FunctionName", MaxThreads])




The number of the message to monitor or query, which should be between 0 and 4294967295 (0xFFFFFFFF). If you do not wish to monitor a system message (that is, one below 0x400), it is best to choose a number greater than 4096 (0x1000) to the extent you have a choice. This reduces the chance of interfering with messages used internally by current and future versions of AutoHotkey.



function's name, which must be enclosed in quotes if it is a literal string. This function will be called automatically when the script receives MsgNumber. Omit this parameter and the next one to retrieve the name of the function currently monitoringMsgNumber (blank if none). Specify an empty string ("") or an empty variable to turn off the monitoring of MsgNumber.



This integer is normally omitted, in which case the monitor function is limited to one thread at a time. This is usually best because otherwise, the script would process messages out of chronological order whenever the monitor function interrupts itself. Therefore, as an alternative to MaxThreads, consider using Critical as described below.

Return Values(결과값)

If FunctionName and MaxThreads are omitted, it returns the name of the function currently monitoring MsgNumber (blank if none). However, no changes are made.

FunctionName MaxThreads 생략하는 경우

현재 MsgNumber (공백인 경우) 모니터링 기능 이름을 반환합니다. 

단, 변경 사항이 있습니다.

If FunctionName is explicitly blank (e.g. ""), it returns the name of the function currently monitoring MsgNumber (blank if none), then disables the monitoring of MsgNumber.

FunctionName 명시적으로 (예 : "") 비어 있으면 다음 MsgNumber 모니터링 

해제, 현재 MsgNumber (공백인 경우) 모니터링 기능 이름을 반환합니다.

If FunctionName is non-blank: If MsgNumber is already being monitored, it returns the name of that function then puts the new function into effect. Otherwise, it assigns FunctionName to monitor MsgNumber then returns the same FunctionName. In either case, a blank value is returned upon failure. Failure occurs when FunctionName: 1) does not exist (perhaps due to missing quotes around FunctionName); 2) accepts more than four parameters; or 3) has any ByRef or optional parameters. It will also fail if the script attempts to monitor a new message when there are already 500 messages being monitored.

FunctionName 공백이 아닌 경우 : MsgNumber 이미 모니터링 중인 경우,  효과에 새로운 기능을 두고 그 함수 이름을 반환합니다.  그렇지 않으면 

MsgNumber 다음 같은 FunctionName 반환 모니터 FunctionName 할당합니다.

어떤 경우이든,  값이 실패 반환됩니다. (아마 FunctionName 주위에 누락된 따옴표 인한) 1)가 존재하지 않습니다; 2) 이상의 네 가지 매개 변수 허용하거나, 3) 어떤 ByRef 또는 선택적 매개 변수가 있습니다 :

 실패 FunctionName  발생합니다.

The Function's Parameters(함수 매개 변수)

function assigned to monitor one or more messages can accept up to four parameters:

MyMessageMonitor(wParam, lParam, msg, hwnd)
    ... body of function...

Although the names you give the parameters do not matter, the following information is sequentially assigned to them:

Parameter #1: The message's WPARAM value, which is an integer between 0 and 4294967295.
Parameter #2: The message's LPARAM value, which is an integer between 0 and 4294967295.
Parameter #3: The message number, which is useful in cases where a function monitors more than one message.
Parameter #4: The HWND (unique ID) of the window or control to which the message was sent. The HWND can be used with ahk_id.

You can omit one or more parameters from the end of the list if the corresponding information is not needed. For 예제, a function defined asMyMsgMonitor(wParam, lParam) would receive only the first two parameters, and one defined as MyMsgMonitor() would receive none of them.

If an incoming WPARAM or LPARAM is intended to be a signed integer, any negative numbers can be revealed by following this 예제:

if wParam > 0x7FFFFFFF
    wParam := -(~wParam) - 1

Additional Information Available to the Function

In addition to the parameters received above, the function may also consult the values in the following built-in variables:

  • A_Gui: Blank unless the message was sent to a GUI window or control, in which case A_Gui is the Gui Window number (this window is also set as the function's default GUI window).
  • A_GuiControl: Blank unless the message was sent to a GUI control, in which case it contains the control's variable name or other value as described at A_GuiControl. Some controls never receive certain types of messages. For 예제, when the user clicks a text control, the operating system sends WM_LBUTTONDOWN to the parent window rather than the control; consequently, A_GuiControl is blank.
  • A_GuiX and A_GuiY: Both contain -2147483648 if the incoming message was sent via SendMessage. If it was sent via PostMessage, they contain the mouse cursor's coordinates (relative to the screen) at the time the message was posted.
  • A_EventInfo: Contains 0 if the message was sent via SendMessage. If sent via PostMessage, it contains the tick-count time the message was posted.

A monitor function's last found window starts off as the parent window to which the message was sent (even if it was sent to a control). If the window is hidden but not a GUI window (such as the script's main window), turn on DetectHiddenWindows before using it. For 예제:

DetectHiddenWindows On
MsgParentWindow := WinExist()  ; This stores the unique ID of the window to which the message was sent.

What the Function Should Return

If a monitor function uses Return without any parameters, or it specifies a blank value such as "" (or it never uses Return at all), the incoming message goes on to be processed normally when the function finishes. The same thing happens if the function Exits or causes a runtime error such as running a nonexistent file. By contrast, returning an integer between -2147483648 and 4294967295 causes that number to be sent immediately as a reply; that is, the program does not process the message any further. For 예제, a function monitoring WM_LBUTTONDOWN (0x201) may return an integer to prevent the target window from being notified that a mouse click has occurred. In many cases (such as a message arriving via PostMessage), it does not matter which integer is returned; but if in doubt, 0 is usually safest.

General Remarks

Unlike a normal function-call, the arrival of a monitored message calls the function as a new thread. Because of this, the function starts off fresh with the default values for settings such as SendMode and DetectHiddenWindows. These defaults can be changed in the auto-execute section.

Messages sent to a control (rather than being posted) are not monitored because the system routes them directly to the control behind the scenes. This is seldom an issue for system-generated messages because most of them are posted.

Any script that calls OnMessage anywhere is automatically persistent. It is also single-instance unless #SingleInstance has been used to override that.

If a message arrives while its function is still running due to a previous arrival of the same message, the function will not be called again (except ifMaxThreads is greater than 1); instead, the message will be treated as unmonitored. If this is undesirable, a message greater than or equal to 0x312 can be buffered until its function completes by specifying Critical as the first line of the function. Alternatively, Thread Interrupt can achieve the same thing as long as it lasts long enough for the function to finish. By contrast, a message less than 0x312 cannot be buffered by Critical or Thread Interrupt (however, in v1.0.46+, Critical may help because it checks messages less often, which gives the function more time to finish). The only way to guarantee that no such messages are missed is to ensure the function finishes in under 6 milliseconds (though this limit can be raised via Critical 30). One way to do this is to have it queue up a future thread by posting to its own script a monitored message number higher than 0x312. That message's function should use Critical as its first line to ensure that its messages are buffered.

If a monitored message that is numerically less than 0x312 arrives while the script is absolutely uninterruptible -- such as while a menu is displayed, aKeyDelay/MouseDelay is in progress, or the clipboard is being opened -- the message's function will not be called and the message will be treated as unmonitored. By contrast, a monitored message of 0x312 or higher will be buffered during these uninterruptible periods; that is, its function will be called when the script becomes interruptible.

If a monitored message numerically less than 0x312 arrives while the script is uninterruptible merely due to the settings of Thread Interrupt or Critical, the current thread will be interrupted so that the function can be called. By contrast, a monitored message of 0x312 or higher will be buffered until the thread finishes or becomes interruptible.

The priority of OnMessage threads is always 0. Consequently, no messages are monitored or buffered when the current thread's priority is higher than 0.

Caution should be used when monitoring system messages (those below 0x400). For 예제, if a monitor function does not finish quickly, the response to the message might take longer than the system expects, which might cause side-effects. Unwanted behavior may also occur if a monitor function returns an integer to suppress further processing of a message, but the system expected different processing or a different response.

When the script is displaying a system dialog such as MsgBox, any message posted to a control is not monitored. For 예제, if the script is displaying a MsgBox and the user clicks a button in a GUI window, the WM_LBUTTONDOWN message is sent directly to the button without calling the monitor function.

Although an external program may post messages directly to a script's thread via PostThreadMessage() or other API call, this is not recommended because the messages would be lost if the script is displaying a system window such as a MsgBox. Instead, it is usually best to post or send the messages to the script's main window or one of its GUI windows.

관련 명령어

RegisterCallback()OnExitOnClipboardChangePost/SendMessageFunctionsList of Windows MessagesThreadsCriticalDllCall()


; 예제: The following is a working script that monitors mouse clicks in a GUI window.
; 관련 명령어 topic: GuiContextMenu

Gui, Add, Text,, Click anywhere in this window.
Gui, Add, Edit, w200 vMyEdit
Gui, Show
OnMessage(0x201, "WM_LBUTTONDOWN")

WM_LBUTTONDOWN(wParam, lParam)
    X := lParam & 0xFFFF
    Y := lParam >> 16
    if A_GuiControl
        Control := "`n(in control " . A_GuiControl . ")"
    ToolTip You left-clicked in Gui window #%A_Gui% at client coordinates %X%x%Y%.%Control%



; 예제: The following script detects system shutdown/logoff and allows you to abort it (this is
; reported NOT to work on Windows Vista).
; 관련 명령어 topic: OnExit

; The following DllCall is optional: it tells the OS to shut down this script first (prior to all other applications).
; This call has no effect on Windows 9x.
DllCall("kernel32.dll\SetProcessShutdownParameters", UInt, 0x4FF, UInt, 0)

    ENDSESSION_LOGOFF = 0x80000000
    if (lParam & ENDSESSION_LOGOFF)  ; User is logging off.
        EventType = Logoff
    else  ; System is either shutting down or restarting.
        EventType = Shutdown
    MsgBox, 4,, %EventType% in progress.  Allow it?
    IfMsgBox Yes
        return true  ; Tell the OS to allow the shutdown/logoff to continue.
        return false  ; Tell the OS to abort the shutdown/logoff.


; 예제: Have a script receive a custom message and up to two numbers from some other script or program
; (to send strings rather than numbers, see the 예제 after this one).

OnMessage(0x5555, "MsgMonitor")
OnMessage(0x5556, "MsgMonitor")

MsgMonitor(wParam, lParam, msg)
    ; Since returning quickly is often important, it is better to use a ToolTip than
    ; something like MsgBox that would prevent the function from finishing:
    ToolTip Message %msg% arrived:`nWPARAM: %wParam%`nLPARAM: %lParam%

; The following could be used inside some other script to run the function inside the above script:
SetTitleMatchMode 2
DetectHiddenWindows On
if WinExist("Name of Receiving Script.ahk ahk_class AutoHotkey")
    PostMessage, 0x5555, 11, 22  ; The message is sent  to the "last found window" due to WinExist() above.
DetectHiddenWindows Off  ; Must not be turned off until after PostMessage.


; 예제: Send a string of any length from one script to another.  This is a working 예제.
; To use it, save and run both of the following scripts then press Win+Space to show an
; InputBox that will prompt you to type in a string.

; Save the following script as "Receiver.ahk" then launch it:
OnMessage(0x4a, "Receive_WM_COPYDATA")  ; 0x4a is WM_COPYDATA

Receive_WM_COPYDATA(wParam, lParam)
    StringAddress := NumGet(lParam + 8)  ; lParam+8 is the address of CopyDataStruct's lpData member.
    StringLength := DllCall("lstrlen", UInt, StringAddress)
    if StringLength <= 0
        ToolTip %A_ScriptName%`nA blank string was received or there was an error.
        VarSetCapacity(CopyOfData, StringLength)
        DllCall("lstrcpy", "str", CopyOfData, "uint", StringAddress)  ; Copy the string out of the structure.
        ; Show it with ToolTip vs. MsgBox so we can return in a timely fashion:
        ToolTip %A_ScriptName%`nReceived the following string:`n%CopyOfData%
    return true  ; Returning 1 (true) is the traditional way to acknowledge this message.

; Save the following script as "Sender.ahk" then launch it.  After that, press the Win+Space hotkey.
TargetScriptTitle = Receiver.ahk ahk_class AutoHotkey

#space::  ; Win+Space hotkey. Press it to show an InputBox for entry of a message string.
InputBox, StringToSend, Send text via WM_COPYDATA, Enter some text to Send:
if ErrorLevel  ; User pressed the Cancel button.
result := Send_WM_COPYDATA(StringToSend, TargetScriptTitle)
if result = FAIL
    MsgBox SendMessage failed. Does the following WinTitle exist?:`n%TargetScriptTitle%
else if result = 0
    MsgBox Message sent but the target window responded with 0, which may mean it ignored it.

Send_WM_COPYDATA(ByRef StringToSend, ByRef TargetScriptTitle)  ; ByRef saves a little memory in this case.
; This function sends the specified string to the specified window and returns the reply.
; The reply is 1 if the target window processed the message, or 0 if it ignored it.
    VarSetCapacity(CopyDataStruct, 12, 0)  ; Set up the structure's memory area.
    ; First set the structure's cbData member to the size of the string, including its zero terminator:
    NumPut(StrLen(StringToSend) + 1, CopyDataStruct, 4)  ; OS requires that this be done.
    NumPut(&StringToSend, CopyDataStruct, 8)  ; Set lpData to point to the string itself.
    Prev_DetectHiddenWindows := A_DetectHiddenWindows
    Prev_TitleMatchMode := A_TitleMatchMode
    DetectHiddenWindows On
    SetTitleMatchMode 2
    SendMessage, 0x4a, 0, &CopyDataStruct,, %TargetScriptTitle%  ; 0x4a is WM_COPYDATA. Must use Send not Post.
    DetectHiddenWindows %Prev_DetectHiddenWindows%  ; Restore original setting for the caller.
    SetTitleMatchMode %Prev_TitleMatchMode%         ; Same.
    return ErrorLevel  ; Return SendMessage's reply back to our caller.


; 예제: See the WinLIRC client script for a demonstration of how to use OnMessage() to receive
; notification when data has arrived on a network connection.

로그인 후 댓글쓰기가 가능합니다.


List of Articles
번호 분류 제목 날짜 조회 수
453 프로세스 JQS.EXE jusched.exe (JavaQuickStarterService) 부팅시 자동실행 중지시키기 4 2011.02.06 11693
452 프로세스 dgdersvc.exe 서비스 중지 및 사용안함, 삭제 설정 1 4 2011.02.06 20904
451 AutoHotKey Mysqld 프로세서 실시간 감시 2011.02.06 6847
» AutoHotKey OnMessage() 3 2011.02.05 18700
449 AutoHotKey [autohotkey] TCP/IP 메시지 전달방법 2011.02.05 12350
448 컴퓨터잡담 언인스톨 사용하기 1 2011.02.05 3555
447 AutoHotKey [autohotkey] FTP-업로드 예제분석 2 file 2011.02.05 15899
446 AutoHotKey [AUTOHOTKEY] FTP 제어 file 2011.02.04 21870
445 Visual C++ IOStream 함수 13 2011.01.29 16505
444 Visual C++ 객체지향 2 2011.01.29 20360
Board Pagination Prev 1 ... 167 168 169 170 171 ... 214 Next
/ 214


sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내

이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소