(原) golang操作Win的API

原创文章,请后转载,并注明出处。

对 github.com/lxn/win 做了一点点学习,进行win操作。

package main

import (
	"fmt"
	"os/exec"
	"runtime"

	"github.com/lxn/win"
	"github.com/webview/webview"
)

const DESKTOP_SWITCHDESKTOP = 0x0100 // The access to the desktop

var (
	ScreenWidth  int32
	ScreenHeight int32
	WinWidth     int
	WinHeight    int
)

func init() {
	WinWidth = 800
	WinHeight = 500
}

func main() {
	debug := true

	w := webview.New(debug)
	hWnd := win.HWND(w.Window())
	win.AnimateWindow(hWnd, 1, win.AW_HIDE|win.AW_CENTER)
	defer w.Destroy()

	// 获取系统参数:屏幕大小
	ScreenWidth = win.GetSystemMetrics(win.SM_CXSCREEN)
	ScreenHeight = win.GetSystemMetrics(win.SM_CYSCREEN)
	win.MoveWindow(hWnd, 0, 0, ScreenWidth, ScreenHeight, true) // 移动窗口位置和大小
	w.SetTitle("Minimal webview example")
	w.Navigate("https://i.scwy.net")
	//w.SetSize(int(ScreenHeight), int(ScreenHeight), webview.HintNone) // 窗口大小
	win.AnimateWindow(hWnd, 700, win.AW_BLEND) // 渐显
	win.MessageBeep(win.MB_OK)                 // 播放完成声音

	// 信息框
	// Text := syscall.StringToUTF16Ptr("测试内容")
	// Caption := syscall.StringToUTF16Ptr("测试")
	// ret := win.MessageBox(hWnd, Text, Caption, win.MB_YESNO)
	// if ret == win.IDYES {
	// 	fmt.Println("点击YES")
	// } else if ret == win.IDNO {
	// 	fmt.Println("点击NO")
	// }

	var old_press int16
	go func() {
		for {
			press := win.GetKeyState(win.VK_CONTROL)

			if press != old_press {
				if press > 0 {
					fmt.Println("没按")
				} else if press < 0 {
					fmt.Println("按下")
				}
				old_press = press
			}
		}
	}()

	// 获取鼠标位置
	// go func() {
	// 	var old_point win.POINT
	// 	for {
	// 		var point win.POINT
	// 		win.GetCursorPos(&point)
	// 		if old_point != point {
	// 			fmt.Println(point)
	// 			old_point = point
	// 		}
	// 	}
	// }()

	// 查找窗口
	// hwnd, err = GetWindowHwndByName("firfox.exe")
	// hWnd = win.HWND(unsafe.Pointer(hwnd))
	// if IsMyWindowsHwnd(hWnd) {}

	// win.SetWindowPos(hWnd, win.HWND_TOPMOST, 0, 0, 0, 0, win.SWP_NOMOVE|win.SWP_NOSIZE) // 置顶
	// win.SetWindowPos(hWnd, win.HWND_NOTOPMOST, 0, 0, 0, 0, win.SWP_NOMOVE|win.SWP_NOSIZE) // 不置顶
	// style := win.GetWindowLong(hWnd, win.GWL_STYLE) // 普通窗口样式
	// style &= ^win.WS_SIZEBOX & ^win.WS_CAPTION // 无边框
	// style |= win.WS_SIZEBOX | win.WS_CAPTION        // 有边框
	// win.SetWindowLong(hWnd, win.GWL_STYLE, style)   // 设置样式
	// win.MoveWindow(hWnd, int32(-10), int32(-10), int32(1), int32(1), true) // 移动窗口位置和大小

	// win.SendMessage(hWnd, win.WM_KEYDOWN, 0x0000007A, 0x20380001) // 按下按键
	// win.SendMessage(hWnd, win.WM_KEYUP, 0x0000007A, 0x003C0001)   // 抬起按键

	w.Run()
}

// 打开浏览器
func OpenWithBrowser(url string) error {
	switch runtime.GOOS {
	case "linux":
		return exec.Command("xdg-open", url).Start()
	case "windows":
		return exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()

	case "darwin":
		return exec.Command("open", url).Start()
	default:
		return fmt.Errorf("runtime.GOOS %s is not supported", runtime.GOOS)

	}
}

相关文章