Sciter之子线程更新UI(八)

通常gui框架主线程负责更新UI,子线程可以通过post方法到主线程更新UI,子线程无法直接更新UI

本文章将介绍在子线程中更新UI、操作dom等,适用于耗时任务场景,例如子线程下载文件,完成后更新UI。

前言

Sciter 是一个高质量但小众的嵌入式 UI 引擎,适合追求性能、体积和原生集成的桌面应用开发者。

我觉得 Sciter 比较有意思,它很小众,是闭源的,商用需要许可。它是Andrew Fedoniouk开发维护,Andrew获得了物理学和应用数学硕士学位以及艺术文凭。他的职业生涯始于俄罗斯航空航天工业的研究员。这种跨领域背景使他既具备深厚的技术功底,又懂得用户界面设计的艺术。

本次入门开发环境:window 10 + Clion 2024.3 + Sciter-js v6.0.2.28(2025-11-15最新版) + Bundled MinGW 11.0 不了解的同学可以参考入门:https://lingkang.top/archives/sciter-ru-men-zhi-hello-yi

Sciter子线程中更新UI

在子线程中调用 sciter::thread线程即可更新UI,例如

c++后端

// sciter::window 创建时全局存储好
sciter::window *global_window;

// main 中:
// 创建ui窗口实例
sciter::om::hasset<mainWindow> window = new mainWindow();
// set global
global_window = window;


// 方法中执行线程逻辑如下.......

std::string data="我要更新UI";

// 定义一个线程
std::thread([data](){
	Sleep(5000);// 模拟子线程延迟
	
	// 逻辑处理完毕,sciter::thread线程更新UI
	sciter::thread([data](sciter::window *win) {
		sciter::dom::element root = win->root();
		sciter::value json;
		json.set_item("type", "updateUI");
		json.set_item("data", data);
		root.post_event(L"cxx_event", json);// 发送事件通知
	}, global_window);// global_window 为sciter::window 创建时全局存储好
	
}).detach();// 剥离线程

html 前端

// 监听c++发送的事件
Window.this.on("cxx_event", function (event) {
	const data = event.data
	console.log(data)
	// 根据数据做出不同更新操作
})

其他

除了上面使用事件通知前端更新,你还可以:

sciter::thread 调用方法更新:

c++

// 逻辑处理完毕,sciter::thread线程更新UI
sciter::thread([data](sciter::window *win) {
	// 入参,只有一个
	VALUE argvs[1];
	LPCWSTR chars = L"入参字符串:lingkang";
	ValueStringDataSet(&argvs[0], chars, wcslen(chars), 0);
	VALUE result;
	// 调用前端js定义的 my_js_fun 方法
	SCDOM_RESULT ok = SciterCallScriptingFunction(win->root(), "my_js_fun", argvs, 1, &result);
	if (ok == SCDOM_OK) {
	   LPCWSTR str_data;
	  UINT str_length;
	  ValueStringData(&result, &str_data, &str_length);
		// 获取字符串数据
		std::wcout << "调用js的结果: " << str_data << std::endl;
	} else {
		// 处理错误
		std::cout << "调用js出错啦 " << std::endl;
	}

	// 清理
	ValueClear(&result);
	ValueClear(&argvs[0]);
}, global_window);// global_window 为sciter::window 创建时全局存储好

前端如下

// 定义一个js方法给c++调用
function my_js_fun(param) {
	console.log('js方法被调用' + param);
	return '你的入参是:' + param
}