Golang GUI开发之Webview
咻兔哔 / 技术文章

Golang GUI开发之Webview

学习Golang 也有一段时间了, 写爬虫、写命令行、写Web 都尝试过了, 简洁的语法强悍的协程写起什么东西都很得心应手,唯独在客户端这里有点受挫.

​首先日常电脑使用环境 Mac 和 Windows 经常切换,一些小工具也都考虑跨平台所以 自己开发小工具的时候都是考虑跨平台,结果显而易见并不是那么顺利.

尝试过fyne,go-gtk,go-sciter,wails,ui,QT
当然在https://awesome-go.com/#gui
这个上面的几乎都尝试了下,怎么来说呢,就是不太好用,要么不能达到想要的界面效果 要么缺少关键功能

好了言归正传,在不断的尝试过程中也有些发现,先说下`webview/webview`

这个包,就是一个浏览器壳子 里面套用HTML代码,使用各种CSS框架 或者VUE等技术都可以实现想要的效果
wails就是用这个封装的,不过现在的版本不在支持各种系统API调用,
例如: 文件选择,文件夹选择
闲逛github的时候发现了一个跨平台简易的包

github.com/sqweek/dialog支持文件选择,对话框,文件夹选择,简单的API封装结合
webview/webview用可以达到想要的效果,在然后就是在webview/webview渲染出来的HTML不支持键盘操作,
例如: command+c,command+v,command+a等等,
这个在webview/webview的issuse下发现有人也提出了疑问,而且在下面找到了一个临时的解决方案就是初始化的时候注入监听代码如下:

const copyPasteShortcut = `
			window.addEventListener("keypress", (event) => {
				if (event.metaKey && event.key === 'c') {
					document.execCommand("copy")
					event.preventDefault();
				}
				if (event.metaKey && event.key === 'v') {
					document.execCommand("paste")
					event.preventDefault();
				}
				if (event.metaKey && event.key === 'a') {
					document.execCommand("selectAll")
					event.preventDefault();
			  	}
				
			})
			`

	w.Eval(copyPasteShortcut)

下图就是我想实现的效果啦,一个输入框,一个文件夹选择器,如果本篇文章对您有帮助,那么我也会很高兴,感谢!

xiaoguo.png

用到的包:

  1. [http://github.com/sqweek/dialog](http://github.com/sqweek/dialog)

Simple cross-platform dialog API for go-lang

examples

ok := dialog.Message("%s", "Do you want to continue?").Title("Are you sure?").YesNo()
filename, err := dialog.File().Filter("Mp3 audio file", "mp3").Load()
directory, err := dialog.Directory().Title("Load images").Browse()
  1. [http://github.com/webview/webview](http://github.com/webview/webview)

    A tiny cross-platform webview library for C/C++/Golang to build modern cross-platform GUIs. Also, there are Rust bindings, Python bindings, Nim bindings, Haskell, C# bindings and Java bindings available.

    The goal of the project is to create a common HTML5 UI abstraction layer for the most widely used platforms.

    It supports two-way JavaScript bindings (to call JavaScript from C/C++/Go and to call C/C++/Go from JavaScript).

    It uses Cocoa/WebKit on macOS, gtk-webkit2 on Linux and Edge on Windows 10.

    package main
    
    import "github.com/webview/webview"
    
    func main() {
    	debug := true
    	w := webview.New(debug)
    	defer w.Destroy()
    	w.SetTitle("Minimal webview example")
    	w.SetSize(800, 600, webview.HintNone)
    	w.Navigate("https://en.m.wikipedia.org/wiki/Main_Page")
    	w.Run()
    }
    
    
支付宝捐赠
请使用支付宝扫一扫进行捐赠
微信捐赠
请使用微信扫一扫进行赞赏
有 0 篇文章