使用 javascript 形式的 windows 桌面通知

desktop notification using javascript in windows form

我是新手,我正在创建一个简单的应用程序,我在其中单击一个按钮,桌面上应该会显示一条通知。我在 windows form c#

中这样做

错误是“NullReferenceException was unhandled

我在 form1 中有一个按钮 Notify。我试过这个:

form1.cs

     public Form1()
            {
                InitializeComponent();
                this.Load += new EventHandler(Form1_Load);
                webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
                webBrowser1.ScriptErrorsSuppressed = true;
            }

            private void btnNotify_Click(object sender, EventArgs e)
            {
                webBrowser1.Document.InvokeScript("notifyMe");
            } 

 private void Form1_Load(object sender, EventArgs e)
        {
            string CurrentDirectory = Directory.GetCurrentDirectory();
            webBrowser1.Navigate(Path.Combine(CurrentDirectory,"HTMLPage1.html"));
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.ObjectForScripting = this;

HTMLPage1.html 代码:

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script language="javascript" type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
    if (Notification.permission !== "granted")
    Notification.requestPermission();
    });

    function notifyMe() {
    if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.');
    return;
    }

    if (Notification.permission !== "granted")
    Notification.requestPermission();
    else {
    var notification = new Notification('Notification title', {
    icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
    body: "Hey there! You've been notified!",
    });

    notification.onclick = function () {
    window.open("");
    };

    }

    }
    </script>
</head>
<body>

</body>
</html>

即使我只是将 alert("Hi") 放在 notifyMe() 函数中,也没有别的。仍然显示相同的错误。

我试过你的代码..你应该使用

document.attachEvent('DOMContentLoaded', function () {..

而不是

document.addEventListener("..

从这里开始工作......在这里阅读更多关于它的信息

您还应该删除 .. body: "Hey there! You've been notified!", 末尾的那个逗号,因为它会阻止脚本被编译。

如果您的 html 和脚本没有自动放置,您必须将它们放在调试目录中。这就是 getcurrentdirectory() 命中的地方。