-
Notifications
You must be signed in to change notification settings - Fork 4
/
consolesize_windows.go
74 lines (64 loc) · 1.67 KB
/
consolesize_windows.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// +build windows, !unix
package consolesize
import (
"fmt"
"syscall"
"unsafe"
)
type (
short int16
word uint16
smallRect struct {
Left short
Top short
Right short
Bottom short
}
coord struct {
X short
Y short
}
consoleScreenBufferInfo struct {
Size coord
CursorPosition coord
Attributes word
Window smallRect
MaximumWindowSize coord
}
)
var kernel32DLL = syscall.NewLazyDLL("kernel32.dll")
var getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo")
// GetConsoleSize returns the current number of columns and rows in the active console window.
// The return value of this function is in the order of cols, rows.
func GetConsoleSize() (int, int) {
stdoutHandle := getStdHandle(syscall.STD_OUTPUT_HANDLE)
var info, err = getConsoleScreenBufferInfo(stdoutHandle)
if err != nil {
return 0, 0
}
return int(info.Window.Right - info.Window.Left + 1), int(info.Window.Bottom - info.Window.Top + 1)
}
func getError(r1, r2 uintptr, lastErr error) error {
// If the function fails, the return value is zero.
if r1 == 0 {
if lastErr != nil {
return lastErr
}
return syscall.EINVAL
}
return nil
}
func getStdHandle(stdhandle int) uintptr {
handle, err := syscall.GetStdHandle(stdhandle)
if err != nil {
panic(fmt.Errorf("could not get standard io handle %d", stdhandle))
}
return uintptr(handle)
}
func getConsoleScreenBufferInfo(handle uintptr) (*consoleScreenBufferInfo, error) {
var info consoleScreenBufferInfo
if err := getError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)); err != nil {
return nil, err
}
return &info, nil
}