开始

我在很久以前研究过这个东西,但实际上没用什么应用。

但如果有需求的话,下面的代码或许可以解决你的问题。

此脚本位于仓库:ahk-lib\util\message

代码

  • 发送者
; Usage:
; ```
;   ; Send string of any length
;   Sender.SendStr('Receiver.ahk', 'hello')
;   ; Send a custom message and up to two numbers
;   Sender.SendParam('Receiver.ahk', 10, 20)
; ```
class Sender {

  static SendStr(target, message, timeOutTime := 4000) {
    CopyDataStruct := Buffer(3 * A_PtrSize)

    SizeInBytes := (StrLen(message) + 1) * 2
    NumPut("Ptr", SizeInBytes
      , "Ptr", StrPtr(message)
      , CopyDataStruct, A_PtrSize)

    Prev_DetectHiddenWindows := A_DetectHiddenWindows
    Prev_TitleMatchMode := A_TitleMatchMode
    DetectHiddenWindows True
    SetTitleMatchMode 2

    RetValue := SendMessage(0x4a, 0, CopyDataStruct, , target, , , , timeOutTime) ; WM_COPYDATA.

    DetectHiddenWindows Prev_DetectHiddenWindows
    SetTitleMatchMode Prev_TitleMatchMode
    return RetValue
  }

  static SendParam(targetStr, wprama, lparam, msgCode := 0x5555) {
    Prev_DetectHiddenWindows := A_DetectHiddenWindows
    DetectHiddenWindows True
    if WinExist(targetStr)
      PostMessage 0x5555, wprama, lparam
    DetectHiddenWindows Prev_DetectHiddenWindows
  }
}
  • 接收者
#Requires AutoHotkey v2.0

OnMessage 0x004A, (wParam, lParam, *) => Receiver._Receive_WM_COPYDATA(lParam)

; Usage:
; ```
;   ; Receive string
;   Receiver.OnCopyDataCB := (data) => MsgBox('get data: ' data)
; 
;   ; Receive custom message
;   Receiver.ReceiveParam(0x5555, cb)
;   cb(wParam, lParam, msg, *) {
;    MsgBox "Message " msg " arrived:`nWPARAM: " wParam "`nLPARAM: " lParam
;   }
; ```
class Receiver {

  static OnCopyDataCB := (data) => ToolTip(A_ScriptName "`nReceived the following string:`n" data)

  static ReceiveParam(msgCode, cb) => OnMessage(msgCode, cb)

  static _Receive_WM_COPYDATA(lParam) {
    StringAddress := NumGet(lParam, 2 * A_PtrSize, "Ptr")
    CopyOfData := StrGet(StringAddress)
    SetTimer Receiver.OnCopyDataCB.Bind(CopyOfData), -1
    return true
  }
}

例子

先启动接收脚本,再启动发送脚本。

  • 发送
#Requires AutoHotkey v2.0
#SingleInstance Force

#Include ..\Sender.ahk

Sender.SendStr('Receiver.ahk', 'hello')
Sender.SendParam('Receiver.ahk', 10, 20)
  • 接收
#Requires AutoHotkey v2.0
#SingleInstance Force

#Include ..\Receiver.ahk

Persistent

Receiver.OnCopyDataCB := (data) => MsgBox('get data: ' data)

Receiver.ReceiveParam(0x5555, cb)
cb(wParam, lParam, msg, *) {
  MsgBox "Message " msg " arrived:`nWPARAM: " wParam "`nLPARAM: " lParam
}
posted on 2024-08-03 13:26  落寞的雪  阅读(72)  评论(0编辑  收藏  举报