实现一个简单的窗口隐藏运行的应用程序,需要使用golang的系统库和UI库。
代码实现步骤:
1. 导入必要的系统库和UI库
package main
import (
"syscall"
"time"
"github.com/lxn/win"
)
2. 创建窗口并设置为隐藏
func createAndHideWindow() {
//设置窗口位置及大小
win.CreateWindowEx(0, syscall.StringToUTF16Ptr("Button"), nil,
win.WS_VISIBLE|win.WS_POPUPWINDOW|win.WS_CAPTION|win.WS_SYSMENU,
100, 100, 400, 300, 0, 0, 0, nil)
//获取窗口句柄
hwnd := win.FindWindow(nil, syscall.StringToUTF16Ptr("Button"))
//设置窗口为隐藏
win.ShowWindow(hwnd, win.SW_HIDE)
}
3. 设置程序在后台运行
func setToBackground() {
hwnd := win.FindWindow(nil, syscall.StringToUTF16Ptr("Button"))
//将程序放在后台运行
_, foreThreadID := win.GetWindowThreadProcessId(win.GetForegroundWindow(), nil)
thisThreadID := win.GetCurrentThreadId()
win.AttachThreadInput(thisThreadID, foreThreadID, true)
win.SetForegroundWindow(hwnd)
win.AttachThreadInput(thisThreadID, foreThreadID, false)
win.ShowWindow(hwnd, win.SW_HIDE)
}
4. 完整示例代码:
package main
import (
"syscall"
"time"
"github.com/lxn/win"
)
func createAndHideWindow() {
win.CreateWindowEx(0, syscall.StringToUTF16Ptr("Button"), nil,
win.WS_VISIBLE|win.WS_POPUPWINDOW|win.WS_CAPTION|win.WS_SYSMENU,
100, 100, 400, 300, 0, 0, 0, nil)
hwnd := win.FindWindow(nil, syscall.StringToUTF16Ptr("Button"))
win.ShowWindow(hwnd, win.SW_HIDE)
}
func setToBackground() {
hwnd := win.FindWindow(nil, syscall.StringToUTF16Ptr("Button"))
_, foreThreadID := win.GetWindowThreadProcessId(win.GetForegroundWindow(), nil)
thisThreadID := win.GetCurrentThreadId()
win.AttachThreadInput(thisThreadID, foreThreadID, true)
win.SetForegroundWindow(hwnd)
win.AttachThreadInput(thisThreadID, foreThreadID, false)
win.ShowWindow(hwnd, win.SW_HIDE)
}
func main() {
createAndHideWindow()
setToBackground()
//程序持续运行
for {
time.Sleep(1 * time.Second)
}
}
以上代码实现了一个简单的窗口隐藏运行的应用程序,通过使用系统库和UI库,实现了在后台运行的效果。