using System; using System.Windows.Forms; using Microsoft.Web.WebView2.WinForms; using Microsoft.Owin.Hosting; using VNCServerList.Web; using Microsoft.Web.WebView2.Core; namespace VNCServerList { public partial class Form1 : Form { private WebView2 webView; private IDisposable webApp; public Form1() { InitializeComponent(); this.Text = $"{Application.ProductName} ver {Application.ProductVersion}"; StartWebServer(); InitializeWebView(); } private async void InitializeWebView() { webView = new WebView2(); webView.Dock = DockStyle.Fill; this.Controls.Add(webView); try { await webView.EnsureCoreWebView2Async(null); // JavaScript에서 C# 메서드를 호출할 수 있도록 설정 webView.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived; webView.CoreWebView2.Navigate("http://localhost:8080"); } catch (Exception ex) { MessageBox.Show($"WebView2 초기화 중 오류가 발생했습니다: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private async void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) { try { var message = e.TryGetWebMessageAsString(); if (message == "OPEN_FILE_DIALOG") { var filePath = ShowOpenFileDialog(); if (!string.IsNullOrEmpty(filePath)) { // JavaScript로 결과 전송 (ExecuteScriptAsync 사용) var script = $"window.receiveFilePath('{filePath.Replace("\\", "\\\\")}');"; await webView.CoreWebView2.ExecuteScriptAsync(script); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"WebView2 메시지 처리 오류: {ex.Message}"); } } private string ShowOpenFileDialog() { using (var openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "실행 파일 (*.exe)|*.exe|모든 파일 (*.*)|*.*"; openFileDialog.Title = "VNC Viewer 실행 파일 선택"; openFileDialog.InitialDirectory = @"C:\Program Files"; if (openFileDialog.ShowDialog() == DialogResult.OK) { return openFileDialog.FileName; } } return null; } private void StartWebServer() { try { var options = new StartOptions("http://localhost:8080"); webApp = WebApp.Start(options); } catch (Exception ex) { MessageBox.Show($"웹 서버 시작 중 오류가 발생했습니다: {ex.Message}", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error); } } protected override void OnFormClosing(FormClosingEventArgs e) { webApp?.Dispose(); base.OnFormClosing(e); } } }