using System.Diagnostics; using System.Reflection; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.WinForms; namespace {{IDENT}}; static class Program { [STAThread] static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new MainForm()); } } // One borderless window with WebView2. The game files are embedded resources ("game/") // and answered from https://{{SLUG}}.game/ via WebResourceRequested. // localStorage (saves, settings) lives in %LOCALAPPDATA%\{{IDENT}}\WebView2. // The page talks to the window with chrome.webview.postMessage("maximize"|"minimize"|"quit"|"drag") // - see kit-host.js. From _Tools\Library\web\template. sealed class MainForm : Form { const string AppName = "{{NAME}}"; const string Host = "https://{{SLUG}}.game/"; const double Aspect = 16.0 / 10.0; // start window width / height const string WebView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703"; static readonly string DataDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "{{IDENT}}"); readonly WebView2 web = new() { Dock = DockStyle.Fill, Visible = false, DefaultBackgroundColor = Color.FromArgb(11, 15, 26) }; readonly Label status = new() { Dock = DockStyle.Fill, TextAlign = ContentAlignment.MiddleCenter, Font = new Font("Segoe UI", 12f), ForeColor = Color.FromArgb(160, 160, 160), Text = $"Starte {AppName} …", }; [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool ReleaseCapture(); [System.Runtime.InteropServices.DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); const int WM_NCLBUTTONDOWN = 0xA1, HTCAPTION = 2; public MainForm() { Text = AppName; Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); BackColor = Color.FromArgb(11, 15, 26); FormBorderStyle = FormBorderStyle.None; // the page draws its own window buttons // Start large: 88 % of the screen height, centred on the screen with the mouse. var wa = Screen.FromPoint(Cursor.Position).WorkingArea; int h = (int)(wa.Height * 0.88); int w = Math.Min((int)(h * Aspect), (int)(wa.Width * 0.92)); StartPosition = FormStartPosition.Manual; Bounds = new Rectangle(wa.X + (wa.Width - w) / 2, wa.Y + (wa.Height - h) / 2, w, h); KeyPreview = true; Controls.Add(web); Controls.Add(status); Shown += async (_, _) => await StartAsync(); } async Task StartAsync() { try { Directory.CreateDirectory(DataDir); var args = "--autoplay-policy=no-user-gesture-required"; // GAME_DEBUG_PORT=9333 opens the DevTools protocol (automated tests) if (int.TryParse(Environment.GetEnvironmentVariable("GAME_DEBUG_PORT"), out var dbg)) args += $" --remote-debugging-port={dbg}"; var env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataDir, "WebView2"), new CoreWebView2EnvironmentOptions(args)); await web.EnsureCoreWebView2Async(env); var core = web.CoreWebView2; core.Settings.IsStatusBarEnabled = false; core.Settings.AreDefaultContextMenusEnabled = false; core.Settings.IsZoomControlEnabled = false; core.Settings.AreBrowserAcceleratorKeysEnabled = false; #if DEBUG core.Settings.AreDevToolsEnabled = true; #else core.Settings.AreDevToolsEnabled = false; #endif core.AddWebResourceRequestedFilter(Host + "*", CoreWebView2WebResourceContext.All); core.WebResourceRequested += (_, e) => e.Response = Serve(core.Environment, e.Request.Uri); // links with target=_blank open in the normal browser core.NewWindowRequested += (_, e) => { e.Handled = true; if (e.Uri.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) try { Process.Start(new ProcessStartInfo(e.Uri) { UseShellExecute = true }); } catch { } }; core.NavigationStarting += (_, e) => { if (!e.Uri.StartsWith(Host)) e.Cancel = true; }; core.WebMessageReceived += (_, e) => { switch (e.TryGetWebMessageAsString()) { case "maximize": ToggleFullscreen(); break; case "minimize": WindowState = FormWindowState.Minimized; break; case "quit": Close(); break; case "drag": if (WindowState == FormWindowState.Normal && (MouseButtons & MouseButtons.Left) != 0) { ReleaseCapture(); SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, IntPtr.Zero); } break; } }; web.Source = new Uri(Host + "index.html"); web.Visible = true; status.Visible = false; } catch (WebView2RuntimeNotFoundException) { status.Text = $"Es fehlt die „Microsoft Edge WebView2 Runtime“.\n\nHier klicken zum Herunterladen, danach {AppName} neu starten."; status.Cursor = Cursors.Hand; status.Click += (_, _) => { try { Process.Start(new ProcessStartInfo(WebView2Download) { UseShellExecute = true }); } catch { } }; } catch (Exception ex) { status.Text = $"{AppName} konnte nicht starten:\n\n" + ex.Message; status.ForeColor = Color.FromArgb(220, 60, 60); } } // Resource names from %(RecursiveDir) contain backslashes - map "game/a/b.png" -> real name. static readonly Dictionary Resources = Assembly.GetExecutingAssembly() .GetManifestResourceNames() .ToDictionary(n => n.Replace('\\', '/'), n => n, StringComparer.OrdinalIgnoreCase); static CoreWebView2WebResourceResponse Serve(CoreWebView2Environment env, string uri) { var path = Uri.UnescapeDataString(new Uri(uri).AbsolutePath.TrimStart('/')); if (path.Length == 0) path = "index.html"; var stream = Resources.TryGetValue("game/" + path, out var name) ? Assembly.GetExecutingAssembly().GetManifestResourceStream(name) : null; if (stream == null) return env.CreateWebResourceResponse(null, 404, "Not Found", ""); var mem = new MemoryStream(); stream.CopyTo(mem); mem.Position = 0; return env.CreateWebResourceResponse(mem, 200, "OK", $"Content-Type: {Mime(path)}\nContent-Length: {mem.Length}\nCache-Control: no-cache"); } static string Mime(string path) => Path.GetExtension(path).ToLowerInvariant() switch { ".html" => "text/html; charset=utf-8", ".js" or ".mjs" => "text/javascript", ".css" => "text/css", ".json" => "application/json", ".png" => "image/png", ".jpg" or ".jpeg" => "image/jpeg", ".webp" => "image/webp", ".svg" => "image/svg+xml", ".mp3" => "audio/mpeg", ".ogg" => "audio/ogg", ".wav" => "audio/wav", ".ttf" => "font/ttf", ".otf" => "font/otf", ".woff2" => "font/woff2", _ => "application/octet-stream", }; protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData == Keys.F11 || keyData == (Keys.Alt | Keys.Enter)) { ToggleFullscreen(); return true; } return base.ProcessCmdKey(ref msg, keyData); } // Borderless window: maximised = covers the whole screen incl. taskbar. void ToggleFullscreen() => WindowState = WindowState == FormWindowState.Maximized ? FormWindowState.Normal : FormWindowState.Maximized; }