-
[WinForms WebBrowser] 자바스크립트에서 C# 메소드를 호출하는 방법닷넷/WinForms 2022. 8. 3. 13:50반응형
namespace WindowsFormsApplication6 { // This first namespace is required for the ComVisible attribute used on the ScriptManager class. using System.Runtime.InteropServices; using System.Windows.Forms; // This is your form. public partial class Form1 : Form { // This nested class must be ComVisible for the JavaScript to be able to call it. [ComVisible(true)] public class ScriptManager { // Variable to store the form of type Form1. private Form1 mForm; // Constructor. public ScriptManager(Form1 form) { // Save the form so it can be referenced later. mForm = form; } // This method can be called from JavaScript. public void MethodToCallFromScript() { // Call a method on the form. mForm.DoSomething(); } // This method can also be called from JavaScript. public void AnotherMethod(string message) { MessageBox.Show(message); } } // This method will be called by the other method (MethodToCallFromScript) that gets called by JavaScript. public void DoSomething() { // Indicate success. MessageBox.Show("It worked!"); } // Constructor. public Form1() { // Boilerplate code. InitializeComponent(); // Set the WebBrowser to use an instance of the ScriptManager to handle method calls to C#. webBrowser1.ObjectForScripting = new ScriptManager(this); // Create the webpage. webBrowser1.DocumentText = @"<html> <head> <title>Test</title> </head> <body> <input type=""button"" value=""Go!"" onclick=""window.external.MethodToCallFromScript();"" /> <br /> <input type=""button"" value=""Go Again!"" onclick=""window.external.AnotherMethod('Hello');"" /> </body> </html>"; } } }
출처: https://www.codeproject.com/Tips/130267/Call-a-C-Method-From-JavaScript-Hosted-in-a-WebBro
반응형'닷넷 > WinForms' 카테고리의 다른 글
C# WinForms DevExpress GridControl에 체크박스 칼럼 (헤더 포함) 추가하기 (0) 2022.12.12 C# DevExpress GridControl 열 전체 선택, 헤더에 체크박스 넣는 법 (0) 2022.08.25 C# WebBrowser IE버전 알맞게 변경하는 방법 (0) 2022.08.03 C# WebBrowser 쿠키 삭제 방법 (0) 2022.08.03 C# WinForms DevExpress GridControl multi header (Banded Grid Views) (0) 2022.03.21