用golang实现windterm中rz命令弹出文件选择框功能
时间: 2023-07-16 20:16:33 浏览: 97
弹出选择文件
5星 · 资源好评率100%
要实现WindTerm中rz命令弹出文件选择框的功能,需要使用go语言编写一个WinAPI程序,并在WindTerm中调用它。以下是基本的代码示例:
```go
package main
import (
"fmt"
"syscall"
"unsafe"
)
var (
comdlg32 = syscall.NewLazyDLL("comdlg32.dll")
getOpenFileName = comdlg32.NewProc("GetOpenFileNameW")
getSaveFileName = comdlg32.NewProc("GetSaveFileNameW")
ole32 = syscall.NewLazyDLL("ole32.dll")
coTaskMemFree = ole32.NewProc("CoTaskMemFree")
shell32 = syscall.NewLazyDLL("shell32.dll")
dragQueryFileW = shell32.NewProc("DragQueryFileW")
dragFinish = shell32.NewProc("DragFinish")
shellExecuteExW = shell32.NewProc("ShellExecuteExW")
shellNotifyIconW = shell32.NewProc("Shell_NotifyIconW")
shellGetImageLists = shell32.NewProc("SHGetImageList")
user32 = syscall.NewLazyDLL("user32.dll")
sendMessageW = user32.NewProc("SendMessageW")
postMessageW = user32.NewProc("PostMessageW")
)
type openfilename struct {
structSize uint32
hwndOwner uintptr
hInstance uintptr
filter *uint16
customFilter *uint16
maxCustomFilter uint32
filterIndex uint32
file *uint16
maxFile uint32
fileTitle *uint16
maxFileTitle uint32
initialDir *uint16
title *uint16
flags uint32
fileOffset uint16
fileExtension uint16
defExt *uint16
custData uintptr
hook uintptr
templateName *uint16
reserved uintptr
flagsEx uint32
}
func rzFileDialog() (string, error) {
var ofn openfilename
ofn.structSize = uint32(unsafe.Sizeof(ofn))
ofn.flags |= 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 // OFN_EXPLORER | OFN_NOCHANGEDIR | OFN_ALLOWMULTISELECT | OFN_PATHMUSTEXIST
ofn.filter = syscall.StringToUTF16Ptr("All Files (*.*)\x00*.*\x00\x00")
ofn.file = syscall.StringToUTF16Ptr(string(make([]uint16, 8192)))
ofn.maxFile = uint32(len([]uint16(*ofn.file)))
ofn.fileTitle = syscall.StringToUTF16Ptr(string(make([]uint16, 8192)))
ofn.maxFileTitle = uint32(len([]uint16(*ofn.fileTitle)))
ret, _, _ := getOpenFileName.Call(uintptr(unsafe.Pointer(&ofn)))
if ret == 0 {
return "", syscall.GetLastError()
}
defer coTaskMemFree.Call(uintptr(unsafe.Pointer(ofn.file)))
defer coTaskMemFree.Call(uintptr(unsafe.Pointer(ofn.fileTitle)))
return syscall.UTF16ToString((*[8192]uint16)(unsafe.Pointer(ofn.file))[:]), nil
}
func main() {
file, err := rzFileDialog()
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Selected file:", file)
}
```
在WindTerm中,可以使用以下命令来调用此程序:
```
rz | go run filedialog.go
```
这将在WindTerm中启动rz命令,并弹出文件选择框。选择文件后,程序将在WindTerm中输出所选文件的路径。
阅读全文