最新消息

欢迎来到 AIMWARE中文网

立即加入我们以访问我们的所有功能。 注册并登录后,您将能够创建主题、发布对现有主题的回复、为您的其他成员提供声誉、获得您自己的私人信使等等。 快捷而且完全免费,你还在等什么?

最新帖子

教程 代码随笔-通过FFI调用浏览器打开指定链接

状态
不接受进一步回复。

An

超级管理员
管理成员
超级管理员
版主
注册
2022-07-07
消息
32
反馈评分
11
点数
8
积分
1,978
    Windows 10 Chrome 125.0.0.0
  • #1
使用了CreateProcess,本段代码只做示例,重复加载可能导致崩溃,请将函数的应用写入到按钮中即可做到点击按钮打开链接
OpenUrl:
local ffi = assert(ffi, "请在Lua安全设置中启用FFI")

ffi.cdef[[
typedef struct _STARTUPINFOW {
    unsigned long cb;
    wchar_t* lpReserved;
    wchar_t* lpDesktop;
    wchar_t* lpTitle;
    unsigned long dwX;
    unsigned long dwY;
    unsigned long dwXSize;
    unsigned long dwYSize;
    unsigned long dwXCountChars;
    unsigned long dwYCountChars;
    unsigned long dwFillAttribute;
    unsigned long dwFlags;
    unsigned short wShowWindow;
    unsigned short cbReserved2;
    unsigned char* lpReserved2;
    void* hStdInput;
    void* hStdOutput;
    void* hStdError;
} STARTUPINFOW, *LPSTARTUPINFOW;

typedef struct _PROCESS_INFORMATION {
    void* hProcess;
    void* hThread;
    unsigned long dwProcessId;
    unsigned long dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;

typedef int BOOL;
typedef const wchar_t* LPCWSTR;
typedef unsigned long DWORD;

BOOL CreateProcessW(
    LPCWSTR lpApplicationName,
    LPCWSTR lpCommandLine,
    void* lpProcessAttributes,
    void* lpThreadAttributes,
    BOOL bInheritHandles,
    DWORD dwCreationFlags,
    void* lpEnvironment,
    LPCWSTR lpCurrentDirectory,
    LPSTARTUPINFOW lpStartupInfo,
    LPPROCESS_INFORMATION lpProcessInformation
);

void GetStartupInfoW(LPSTARTUPINFOW lpStartupInfo);
DWORD WaitForSingleObject(void* hHandle, DWORD dwMilliseconds);
BOOL CloseHandle(void* hObject);

static const int INFINITE = 0xFFFFFFFF;
static const int SW_SHOWNORMAL = 1;
]]

local function utf8_to_utf16(str)
    local len = #str
    local wide_str = ffi.new("wchar_t[?]", len + 1)
    for i = 1, len do
        wide_str[i - 1] = str:byte(i)
    end
    wide_str[len] = 0
    return wide_str
end

local function OpenURL(url)
    local command = 'rundll32 url.dll,FileProtocolHandler ' .. url
    local wcommand = utf8_to_utf16(command)

    local startupInfo = ffi.new("STARTUPINFOW")
    ffi.C.GetStartupInfoW(startupInfo)

    local processInfo = ffi.new("PROCESS_INFORMATION")

    local result = ffi.C.CreateProcessW(
        nil,
        wcommand,
        nil,
        nil,
        false,
        0,
        nil,
        nil,
        startupInfo,
        processInfo
    )

    if result == 0 then
        print("打开URL失败。")
    else
        print("URL打开成功。")
        ffi.C.WaitForSingleObject(processInfo.hProcess, ffi.C.INFINITE)
        ffi.C.CloseHandle(processInfo.hProcess)
        ffi.C.CloseHandle(processInfo.hThread)
    end
end

-- 示例:用系统默认浏览器打开aimware.cn
OpenURL("https://aimware.cn")
 
状态
不接受进一步回复。
顶部 底部