(原) Godot做的一个桌面工具

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

快速的用Godot做了一个桌面工具,用于显示内存占用、CPU占用及网络情况。

代码涉及到多线程,很短,也不够优化。
运行时占用30MB左右,编译后程序大小70MB左右。

extends Control

var is_dragging
var relaty
var thread :Thread
var cpu_per :float = 0.0
var net_speed :float = 0.0
var net_max :float = 0.0
var mutex: Mutex

@onready var progress_bar_1: ProgressBar = $ProgressBar1
@onready var progress_bar_2: ProgressBar = $ProgressBar2
@onready var progress_bar_3: ProgressBar = $ProgressBar3
@onready var lbl_net_speed: Label = $lblNetSpeed

func getCpu() -> void:	
	var cmd = r'typeperf "\Processor Information(_Total)\% Processor Utility" -sc 1'
	var cmd1 = r'typeperf -si 1 -sc 1 "\Network Interface(*)\Bytes Total/sec"'

	while true:
		var output = []
		var output1 = []
		OS.execute("CMD.exe", ["/C", cmd], output)
		OS.execute("CMD.exe", ["/C", cmd1], output1)
		mutex.lock()
		cpu_per = output[0].split("\r\n")[2].split(",")[1].replace("\"","").to_float()
		net_speed = output1[0].split("\r\n")[2].split(",")[1].replace("\"","").to_float()
		mutex.unlock()
		
		OS.delay_msec(500)

func _ready() -> void:
	progress_bar_3.max_value = 100
	var mem = OS.get_memory_info()
	progress_bar_1.max_value = float(mem["physical"])
	
	# 创建新线程,用于更新CPU占用
	mutex = Mutex.new()	
	thread = Thread.new()
	thread.start(getCpu)
		
	var timer = Timer.new()
	timer.autostart = true
	timer.wait_time = 1.0
	timer.timeout.connect(func():
		mem = OS.get_memory_info()
		progress_bar_1.value = float(mem["free"])
		progress_bar_2.value = net_speed
		if net_speed>net_max:
			net_max = net_speed
		progress_bar_2.max_value = net_max
		lbl_net_speed.text = str(int(net_speed/1024)) + "KB"
		progress_bar_3.value = cpu_per
	)	
	add_child(timer)

func _input(event):
	if event is InputEventMouseMotion and is_dragging:
		get_tree().root.position = relaty + DisplayServer.mouse_get_position()

func _process(delta: float) -> void:
	if Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
		if(is_dragging==false):
			var mouse_pos = DisplayServer.mouse_get_position()
			var root_pos = get_tree().root.position
			relaty=(root_pos-mouse_pos)
			#print(relaty)
		is_dragging=true
	else:
		is_dragging=false

func _exit_tree():
	thread.wait_to_finish()

相关文章