2013-06-04 58 views
0

我編譯了一堆在線資源,讓我到這裏。希望我擁有的是接近的。不幸的是,我沒有Windows編程經驗。我來自Linux背景。我對Lua也是alien的新手,但我對Lua的瞭解足夠了。Lua Alien - SendMessage與WinAPI的Notepad.exe

我想要做的是發送一個簡單的「Hello World」sendMessage()Win32 API到正在運行的Notepad.exe窗口。

我從命令提示的進程ID與以下命令:

tasklist /FI "IMAGENAME eq notepad.exe" /FI "USERNAME eq user" 

notepad PID

而且我得到從here發送0x000C的代碼的消息。

到目前爲止,這是我:

require "luarocks.require" 
require "alien" 

myTestMessage = 0x000C -- Notepad "Set text" id 
notepadPID = 2316  -- Notepad Process ID 

-- Prototype the SendMessage function from User32.dll 
local SendMessage= alien.User32.SendMessageA 
SendMessage:types{ret ='long', abi = 'stdcall','long','long','string','string'} 

-- Prototype the FindWindowExA function from User32.dll 
local FindWindowEx = alien.User32.FindWindowExA 
FindWindowEx:types{ret = 'long', abi = 'stdcall', 'long', 'long', 'string', 'string'} 

-- Prototype the GetWindowThreadProcessID function from User32.dll 
local GetWindowThreadProcessId = alien.User32.GetWindowThreadProcessId 
GetWindowThreadProcessId:types{ret = 'long', abi = 'stdcall', 'long', 'pointer'} 

local buffer = alien.buffer(4) -- This creates a 4-byte buffer 

local threadID = GetWindowThreadProcessId(notepadPID, buffer) -- this fills threadID and our 4-byte buffer 

local longFromBuffer = buffer:get(1, 'long') -- this tells that I want x bytes forming a 'long' value and starting at the first byte of the 
          -- 'buffer' to be in 'longFromBuffer' variable and let its type be 'long' 

local handle = FindWindowEx(threadID, "0", "Edit", nil); -- Get the handle to send the message to 

local x = SendMessage(handle, myTestMessage, "0", "Hello World!") -- Actually send the message 

很多這樣的代碼是從Lua alien documentsmsdn拼湊在一起,而一些谷歌搜索(namely this result)。

有沒有人可以成爲英雄,向我解釋我做錯了什麼,以及我應該如何去做這件事。而且,最重要的是,爲什麼!

回答

1

您正在使用GetWindowThreadProcessId()和FindWindowEx()。它們的第一個參數是所需窗口的HWND句柄,但是您將進程ID傳遞給GetWindowThreadProcessId(),並將線程ID傳遞給FindWindowEx(),兩者都是錯誤的。

從進程ID獲取HWND沒有直接的方法。您將不得不使用EnumWindows()循環當前正在運行的窗口,每個窗口都調用GetWindowThreadProcessId(),直到找到與您已有的進程ID相匹配的進程ID。

0

我終於找到了一個更簡單的方法來使用Windows API中的FindWindowFindWindowEX。通過這種方式,您可以找到記事本的父級和子級進程的正確句柄。

-- Require luarocks and alien which are necessray for calling Windows functions 
require "luarocks.require" 
require "alien" 

local SendMessage= alien.User32.SendMessageA 
SendMessage:types{ret ='long', abi = 'stdcall','long','long','string','string'} 

local FindWindowEx = alien.User32.FindWindowExA 
FindWindowEx:types{ret = 'long', abi = 'stdcall', 'long', 'long', 'string', 'string'} 

local FindWindow = alien.User32.FindWindowA 
FindWindow:types{ret = 'long', abi = 'stdcall', 'string', 'string'} 

local notepadHandle = FindWindow("Notepad", NULL) 

local childHandle = FindWindowEx(notepadHandle, "0", "Edit", nil) 

local x = SendMessage(childHandle, "0x000C", "0", "Hello World!") -- Actually send the message