=============== LIBRARY RULES =============== From library maintainers: - This repository is the example repository for https://github.com/twgh/xcgui. - The repository ID for the xcgui library that this repository depends on is /twgh/xcgui. You can use the context7 MCP to fetch source code from the repository with ID /twgh/xcgui. ### Run XCGUI Basic Example with Go Source: https://github.com/twgh/xcgui-example/blob/main/README.md This command sequence demonstrates how to initialize Go modules and run a basic XCGUI window example. It requires Go to be installed and assumes the project structure is as cloned. ```bash go mod tidy go run .\Basic\SimpleWindow\ ``` -------------------------------- ### Bash: Running the Go WebView2 Example Source: https://github.com/twgh/xcgui-example/blob/main/webview/EnvironmentOptions/README.md Provides instructions for compiling and running the Go WebView2 environment options example program. It assumes the necessary WebView2 runtime is installed. ```bash go run EnvironmentOptions.go ``` -------------------------------- ### Download XCGUI Example Project as ZIP Source: https://github.com/twgh/xcgui-example/blob/main/README.md This option provides a direct download link for the XCGUI example project as a ZIP archive. This is useful for users who do not have Git installed or prefer to download the source code manually. ```html 点击下载 ``` -------------------------------- ### Run the Application Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md This bash command executes the `SimpleWebView.go` file using the Go runtime. Ensure you have Go installed and the WebView2 runtime present on your system before running. ```bash go run SimpleWebView.go ``` -------------------------------- ### Show Window and Run Application Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md This Go code snippet displays the application window and starts the XCGUI event loop. The `a.Run()` call keeps the application running until it's closed, and `a.Exit()` performs cleanup after the loop terminates. ```go // Show the window and run the application w.Show(true) a.Run() a.Exit() ``` -------------------------------- ### Basic WebView2 Integration in XCGUI Window (Go) Source: https://context7.com/twgh/xcgui-example/llms.txt This Go code snippet demonstrates how to integrate the WebView2 control into an XCGUI window. It initializes the XCGUI application, creates a WebView environment, and then creates a WebView instance within a window. The example also includes checks for WebView2 runtime installation and version comparison. It navigates the WebView to Baidu.com and displays the window. Dependencies include the XCGUI library and its edge and wapi packages. ```go package main import ( "fmt" "log" "os" "github.com/twgh/xcgui/app" "github.com/twgh/xcgui/edge" "github.com/twgh/xcgui/wapi" ) func main() { checkWebView2() // 初始化界面库 app.InitOrExit() a := app.New(true) a.EnableAutoDPI(true).EnableDPI(true) // 创建 WebView 环境 edg, err := edge.New(edge.Option{ UserDataFolder: os.TempDir(), // 实际应用中应使用自己创建的固定目录 }) if err != nil { wapi.MessageBoxW(0, "创建 WebView 环境失败: "+err.Error(), "错误", wapi.MB_OK|wapi.MB_IconError) os.Exit(1) } // 创建 WebView w, wv, err := edg.NewWebViewWithWindow( edge.WithXmlWindowTitle("简单 WebView 例子"), // 窗口标题 edge.WithXmlWindowSize(1400, 900), // 窗口大小 edge.WithXmlWindowTitleBar(true), // 使用炫彩窗口标题栏 edge.WithFillParent(true), // WebView 填充窗口 edge.WithDebug(true), // 可打开开发者工具 edge.WithAutoFocus(true), // 在窗口获得焦点时尝试保持 WebView 的焦点 ) if err != nil { wapi.MessageBoxW(0, "创建 WebView 失败: "+err.Error(), "错误", wapi.MB_OK|wapi.MB_IconError) os.Exit(2) } // 导航 wv.Navigate("https://www.baidu.com") // 显示窗口并运行应用 w.Show(true) a.Run() a.Exit() } func checkWebView2() { // 输出本库使用的 WebView2 版本 fmt.Println("本库使用的 WebView2 运行时版本号:", edge.GetVersion()) // 获取本机已安装的 WebView2 运行时版本 localVersion, err := edge.GetAvailableBrowserVersion() if err != nil { wapi.MessageBoxW(0, "获取 WebView2 运行时版本号失败: "+err.Error(), "提示", wapi.MB_IconError) os.Exit(1) } if localVersion == "" { wapi.MessageBoxW(0, "请安装 WebView2 运行时后再打开程序! 下载完后请使用管理员权限运行安装包!", "提示", wapi.MB_IconWarning|wapi.MB_OK) // 打开 WebView2 运行时下载页面 edge.DownloadWebView2() os.Exit(2) } fmt.Println("本机安装的 WebView2 运行时版本号:", localVersion) // 检查本机版本是否低于库版本 if ret, _ := edge.CompareBrowserVersions(localVersion, edge.GetVersion()); ret == -1 { log.Println("本机 WebView2 运行时版本低于本库使用的 WebView2 运行时版本!") } } ``` -------------------------------- ### Check WebView2 Runtime Version Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md This Go function checks the installed WebView2 runtime version. It prints the version used by the library, retrieves the locally available version, handles errors, prompts for installation if not found, and checks for version compatibility. This ensures the application uses a compatible WebView2 runtime. ```go func checkWebView2() { // Output the WebView2 version used by this library fmt.Println("WebView2 runtime version used by this library:", edge.GetVersion()) // Get the locally installed WebView2 runtime version localVersion, err := edge.GetAvailableBrowserVersion() if err != nil { // Error handling... } if localVersion == "" { // Prompt to install WebView2 runtime... edge.DownloadWebView2() os.Exit(2) } // Check version compatibility if ret, _ := edge.CompareBrowserVersions(localVersion, edge.GetVersion()); ret == -1 { log.Println("The local WebView2 runtime version is lower than the version used by this library!") } } ``` -------------------------------- ### Initialize XCGUI Application Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md Initializes the XCGUI application, enabling automatic DPI scaling for the application window. This is a prerequisite for creating XCGUI elements. ```go // Initialize the UI library app.InitOrExit() a := app.New(true) a.EnableAutoDPI(true).EnableDPI(true) ``` -------------------------------- ### Navigate WebView to a URL Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md This Go code navigates the created WebView instance (`wv`) to a specific URL. In the example, it navigates to Baidu's homepage. This function is essential for loading web content within the application. ```go // Navigate to Baidu homepage wv.Navigate("https://www.baidu.com") ``` -------------------------------- ### Clone XCGUI Example Project using Git Source: https://github.com/twgh/xcgui-example/blob/main/README.md This snippet shows how to clone the XCGUI example project from GitHub using the git command-line tool. It's the standard method for obtaining the project's source code for local development. ```bash git clone https://github.com/twgh/xcgui-example ``` -------------------------------- ### Get System Info using Go Source: https://github.com/twgh/xcgui-example/blob/main/webview/CustomSchemeRegistration/README.md Retrieves system information by calling a local Go function and updates the WebView with the result. It uses the '/getSystemInfo' custom protocol and expects a JavaScript function 'updateSystemInfo' to be available in the web page. ```go case "/getSystemInfo": info := getSystemInfo() wv.Eval(`updateSystemInfo('` + info + `')`) ``` -------------------------------- ### Go: Outputting WebView2 Environment Configuration Source: https://github.com/twgh/xcgui-example/blob/main/webview/EnvironmentOptions/README.md Prints the current configuration settings of the WebView2 environment to the console. This helps in verifying the applied options after creation. ```go fmt.Println("------------------- WebView2 Environment Options -------------------") fmt.Println("Language:", envOpts.MustGetLanguage()) fmt.Println("Browser Arguments:", envOpts.MustGetAdditionalBrowserArguments()) fmt.Println("Multi-process shared user data folder:", envOpts2.MustGetExclusiveUserDataFolderAccess()) fmt.Println("Tracking prevention:", envOpts5.MustGetEnableTrackingPrevention()) fmt.Println("Browser extensions:", envOpts6.MustGetAreBrowserExtensionsEnabled()) fmt.Println("Channel search type:", envOpts7.MustGetChannelSearchKind()) fmt.Println("Release channels:", envOpts7.MustGetReleaseChannels()) fmt.Println("Scrollbar style:", envOpts8.MustGetScrollBarStyle()) ``` -------------------------------- ### Release COM Objects in Go Source: https://github.com/twgh/xcgui-example/blob/main/webview/CreateByLayoutEle/README.md Demonstrates the use of `defer` to ensure timely release of COM objects in Go, which is crucial for preventing resource leaks. ```go // 及时释放COM对象 defer envOpts.Release() defer stream.Release() ``` -------------------------------- ### Go: WebView2 Release Channels Configuration Source: https://github.com/twgh/xcgui-example/blob/main/webview/EnvironmentOptions/README.md Configures which release channels of WebView2 should be considered during channel search. `COREWEBVIEW2_RELEASE_CHANNELS_NONE` indicates no specific release channels are targeted. ```go ReleaseChannels: &edge.ReleaseChannels{ ReleaseChannels: edge.COREWEBVIEW2_RELEASE_CHANNELS_NONE, } ``` -------------------------------- ### Production User Data Folder Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md This Go code snippet demonstrates the recommended way to set the user data folder for WebView2 in a production environment. It constructs a path using `filepath.Join` and `os.Getenv("APPDATA")` to ensure user data is stored in a consistent and appropriate location, unlike the temporary directory used in the example. ```go // Use a fixed directory in production environments UserDataFolder: filepath.Join(os.Getenv("APPDATA"), "YourAppName") ``` -------------------------------- ### Create WebView Instance (Go) Source: https://github.com/twgh/xcgui-example/blob/main/webview/Chart/README.md Demonstrates how to create a new WebView instance within an XCGUI layout element using the Go edge library. It initializes the WebView and specifies its parent widget. ```go func createWebView1(edg *edge.Edge, wvOption []edge.WebViewOption) { layout_chart := widget.NewLayoutEleByName("layout_chart1") wv, err := edg.NewWebView(layout_chart.Handle, wvOption...) // 配置和事件处理... } ``` -------------------------------- ### Create WebView and Window with Convenient Method Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md This Go code snippet demonstrates the creation of both a window and a WebView2 instance in a single step using the `NewWebViewWithWindow` function. It configures window properties like title and size, enables the title bar, makes the WebView fill the window, enables debugging tools, and sets auto-focus. This is a streamlined approach for simple WebView applications. ```go // Create WebView and window (one step) w, wv, err := edg.NewWebViewWithWindow( edge.WithXmlWindowTitle("Simple WebView Example"), // Window title edge.WithXmlWindowSize(1400, 900), // Window size edge.WithXmlWindowTitleBar(true), // Use custom title bar edge.WithFillParent(true), // WebView fills the window edge.WithDebug(true), // Enable developer tools edge.WithAutoFocus(true), // Auto-focus ) ``` -------------------------------- ### Implement Error Handling for Custom Protocols in Go Source: https://github.com/twgh/xcgui-example/blob/main/webview/CustomSchemeRegistration/README.md This Go code example highlights robust error handling for custom protocol implementations. It includes checks for missing required parameters, validation of parameter formats (e.g., ensuring a path starts with 'C:\'), and proper handling of errors returned from native functions like `wapi.ShellExecuteW`, often by displaying alerts to the user. ```go // 检查必需参数 if path == "" { app.Alert("错误", "缺少 path 参数") return 0 } // 验证参数 if !strings.HasPrefix(path, "C:\\") { app.Alert("错误", "路径必须以 C:\\ 开头") return 0 } // 处理错误 err := wapi.ShellExecuteW(0, "open", filePath, "", "", xcc.SW_SHOW) if err != nil { log.Printf("打开文件失败: %v\n", err) app.Alert("错误", "无法打开文件") } ``` -------------------------------- ### Intercept Navigation and Handle Custom Schemes (Go) Source: https://github.com/twgh/xcgui-example/blob/main/webview/CustomSchemeRegistration/README.md This Go code intercepts the WebView2 navigation starting event to detect and handle custom URI schemes like 'myapp://'. It cancels default navigation and parses the URI to execute specific actions based on the path and query parameters. ```go // Assuming 'wv' is an ICoreWebView2 object and necessary packages are imported. wv.Event_NavigationStarting(func(sender *edge.ICoreWebView2, args *edge.ICoreWebView2NavigationStartingEventArgs) uintptr { // 获取当前导航 URI uri, err := args.GetUri() if err != nil { log.Println("NavigationStarting GetUri 失败:", err) return 0 } fmt.Println("uri:", uri) // 检查是否是自定义协议 if strings.HasPrefix(uri, "myapp://") { // 取消导航,防止 WebView 尝试加载该 URL err := args.SetCancel(true) if err != nil { log.Println("NavigationStarting SetCancel 失败:", err) return 0 } // 解析 URL 并处理 u, err := url.Parse(uri) if err != nil { log.Printf("URL 解析失败: %v\n", err) return 0 } path := "/" + u.Host // 路径,如 "/openFile" query := u.Query() // 查询参数,如 map[string][]string // 根据路径执行不同操作 s switch path { case "/openFile": handleOpenFile(query) case "/showSettings": handleShowSettings() case "/navigateTo": handleNavigateTo(query) default: log.Printf("未知命令: %s\n", path) } } return 0 }) // Placeholder functions for handlers: func handleOpenFile(query map[string][]string) { log.Println("Handling openFile with query:", query) // Implement file opening logic here } func handleShowSettings() { log.Println("Handling showSettings") // Implement show settings logic here } func handleNavigateTo(query map[string][]string) { log.Println("Handling navigateTo with query:", query) // Implement navigation logic here } ``` -------------------------------- ### Create WebView2 Environment Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md Creates a WebView2 environment using the `edge.New` function. This prepares the necessary components for hosting a WebView control. The `UserDataFolder` option specifies where WebView2 will store its data; in production, a fixed directory is recommended over a temporary one. ```go // Create WebView environment edg, err := edge.New(edge.Option{ UserDataFolder: os.TempDir(), // Use a fixed directory in production }) ``` -------------------------------- ### Run Program - Bash Source: https://github.com/twgh/xcgui-example/blob/main/webview/CreateByWindow/README.md 在安装了 WebView2 运行时后,可以通过此命令运行 CreateByWindow.go 程序。程序将自动打开窗口并导航到指定网页。 ```bash go run CreateByWindow.go ``` -------------------------------- ### Go: Manual WebView2 Environment Configuration Source: https://github.com/twgh/xcgui-example/blob/main/webview/EnvironmentOptions/README.md Illustrates manual configuration of WebView2 environment options by creating and configuring `edge.EnvironmentOptions` step-by-step. This approach offers granular control, supports version detection for different options, and requires manual resource management. It's ideal for complex scenarios with specific error handling needs. ```go envOpts, err := edge.CreateEnvironmentOptions() if err != nil { // Handle error } // Set basic options envOpts.SetLanguage("en-us") envOpts.SetAdditionalBrowserArguments(args) // Get and set advanced options (supports version detection) if envOpts2, err := envOpts.GetICoreWebView2EnvironmentOptions2(); err == nil { envOpts2.SetExclusiveUserDataFolderAccess(true) envOpts2.Release() } // ... set other version options edg, err := edge.New(edge.Option{ UserDataFolder: os.TempDir(), EnvironmentOptions: envOpts, }) ``` -------------------------------- ### Customize Navigation URL Source: https://github.com/twgh/xcgui-example/blob/main/webview/SimpleWebView/README.md This Go code snippet shows how to change the web page the WebView navigates to. By modifying the URL string passed to the `wv.Navigate()` function, you can direct the WebView to any desired web address, such as GitHub in this example. ```go // Change Baidu to another website wv.Navigate("https://www.github.com") ``` -------------------------------- ### Implement Global WebView2 Error Handling Source: https://github.com/twgh/xcgui-example/blob/main/webview/CreateByLayoutEle/README.md This Go code configures a global error callback for WebView2. The `SetErrorCallBack` function allows you to define a handler that will be invoked when WebView2 encounters an error. The example shows conditional logging based on a debug flag, differentiating between file-specific and full error messages. ```go // 设置全局WebView错误回调 edge.SetErrorCallBack(func(err *edge.WebViewError) { if isDubug { log.Println(err.ErrorWithFile()) } else { log.Println(err.ErrorWithFullName()) } }) ``` -------------------------------- ### Create WebView and Window with Customization (Go) Source: https://github.com/twgh/xcgui-example/blob/main/webview/CustomSchemeRegistration/README.md This Go code initializes a WebView2 control within a custom window using XCGUI. It demonstrates how to set window properties like title, size, and enable a custom title bar, while ensuring the WebView fills the entire client area of the window. ```go // Assuming 'edg' is an initialized edge.WebView2Environment // and 'wapi' and 'os' are imported packages. // Example usage within a Go program: w, wv, err := edg.NewWebViewWithWindow( edge.WithXmlWindowTitle("注册自定义方案"), edge.WithXmlWindowSize(600, 400), edge.WithXmlWindowTitleBar(true), // 使用炫彩窗口标题栏 edge.WithFillParent(true), // WebView 填充窗口 edge.WithDebug(true), // 启用调试模式 edge.WithAutoFocus(true), // 自动聚焦 ) if err != nil { wapi.MessageBoxW(0, "创建 WebView 和窗口失败: "+err.Error(), "错误", wapi.MB_OK|wapi.MB_IconError) os.Exit(1) } // wv is the ICoreWebView2 object, w is the window handle // Use wv for WebView2 specific operations and w for window management. ``` -------------------------------- ### Create WebView Environment - Go Source: https://github.com/twgh/xcgui-example/blob/main/webview/CreateByWindow/README.md 初始化 WebView2 环境,设置用户数据文件夹。实际应用中应使用固定目录而非临时目录。 ```go // 创建 WebView 环境 edg, err := edge.New(edge.Option{ UserDataFolder: os.TempDir(), // 实际应用应使用固定目录 }) ``` -------------------------------- ### Compile and Run Program (Bash) Source: https://github.com/twgh/xcgui-example/blob/main/webview/Chart/README.md Command to compile and run the Go application. This assumes the necessary Go environment and dependencies are set up. ```bash go run chart.go ``` -------------------------------- ### Go: WebView2 Channel Search Kind Source: https://github.com/twgh/xcgui-example/blob/main/webview/EnvironmentOptions/README.md Specifies the type of WebView2 channel to search for. `COREWEBVIEW2_CHANNEL_SEARCH_KIND_MOST_STABLE` prioritizes the most stable release channel. ```go ChannelSearchKind: edge.COREWEBVIEW2_CHANNEL_SEARCH_KIND_MOST_STABLE // Select the most stable channel version ``` -------------------------------- ### Go: Automatic WebView2 Environment Configuration Source: https://github.com/twgh/xcgui-example/blob/main/webview/EnvironmentOptions/README.md Demonstrates automatic configuration of WebView2 environment options using the `edge.EnvOptions` struct. This method is concise and suitable for stable configurations where resource management is handled automatically. It sets language, browser arguments, and other features in a single structure. ```go edg, err := edge.New(edge.Option{ UserDataFolder: os.TempDir(), EnvOptions: &edge.EnvOptions{ Language: "en-us", AdditionalBrowserArguments: []string{ "--autoplay-policy=no-user-gesture-required", "--disable-features=PreloadMediaEngagementData,MediaEngagementBypassAutoplayPolicies", "--enable-features=AutoplayIgnoreWebAudio", }, ExclusiveUserDataFolderAccess: true, DisableTrackingPrevention: true, AreBrowserExtensionsEnabled: true, ChannelSearchKind: edge.COREWEBVIEW2_CHANNEL_SEARCH_KIND_MOST_STABLE, ScrollBarStyle: edge.COREWEBVIEW2_SCROLLBAR_STYLE_FLUENT_OVERLAY, ReleaseChannels: &edge.ReleaseChannels{ ReleaseChannels: edge.COREWEBVIEW2_RELEASE_CHANNELS_NONE, }, }, }) ``` -------------------------------- ### Go: WebView2 Scrollbar Style Configuration Source: https://github.com/twgh/xcgui-example/blob/main/webview/EnvironmentOptions/README.md Sets the visual style for scrollbars within WebView2. `COREWEBVIEW2_SCROLLBAR_STYLE_FLUENT_OVERLAY` applies a modern, fluent overlay style. ```go ScrollBarStyle: edge.COREWEBVIEW2_SCROLLBAR_STYLE_FLUENT_OVERLAY // Use a modern fluent overlay style ``` -------------------------------- ### Bash: 运行 Go 程序 Source: https://github.com/twgh/xcgui-example/blob/main/webview/SharedBuffer/README.md 使用 `go run` 命令来编译并运行 Go 源代码文件。在此示例中,它用于启动 `SharedBuffer.go` 程序。 ```bash go run SharedBuffer.go ``` -------------------------------- ### WebView2 Environment Options for Performance (Go) Source: https://github.com/twgh/xcgui-example/blob/main/webview/CalcMD5/README.md These Go code snippets demonstrate how to optimize WebView2 performance and user experience. The first example disables tracking prevention for potentially improved runtime performance (use with caution on untrusted content). The second sets a modern, fluent overlay scrollbar style. Dependencies include the edge (WebView2) library. ```Go // 禁用跟踪防护以提高运行时性能(仅在呈现已知安全内容时) envOpts5.SetEnableTrackingPrevention(false) // 设置现代化滚动条样式 envOpts8.SetScrollBarStyle(edge.COREWEBVIEW2_SCROLLBAR_STYLE_FLUENT_OVERLAY) ```