简体   繁体   English

如何使用 c# 执行 Button_Click

[英]How to execute a Button_Click with c#

I've set up a Windows App that runs a code and updates a TextBlock when clicked.我设置了一个 Windows 应用程序,该应用程序运行代码并在单击时更新 TextBlock。 I'm trying to get the button to fire every 2 seconds, whether physically clicked or not.我试图让按钮每 2 秒触发一次,无论是否物理点击。 I'm getting the error:我收到错误:

Error   CS0123  No overload for 'Button_Click' matches delegate 'ElapsedEventHandler'   WpfApp1 C:\Users\User\Documents\Visual Studio 2019\Projects\WpfApp1\WpfApp1\MainWindow.xaml.cs  45      Active

Here is the code这是代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Timers;




namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private static System.Timers.Timer aTimer;

        public MainWindow()
        {

            InitializeComponent();
            SetTimer();
        }

        private static void SetTimer()
        {
            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(2000);
            // Hook up the Elapsed event for the timer.
            aTimer.Elapsed += Button_Click;
            aTimer.AutoReset = true;
            aTimer.Enabled = true;
        }

        public void Button_Click(object sender, RoutedEventArgs e)
        {
            using (WebClient webClient = new System.Net.WebClient())
            {
                var json = webClient.DownloadString("ADDRESS");

                List<string> WhoList = new List<string>();

                JArray parsedArray = JArray.Parse(json);


                foreach (JObject parsedObject in parsedArray.Children<JObject>())
                {
                    foreach (JProperty parsedProperty in parsedObject.Properties())
                    {
                        string propertyName = parsedProperty.Name;
                        if (propertyName.Equals("name"))
                        {
                            string propertyValue = (string)parsedProperty.Value;
                            WhoList.Add(propertyValue);
                        }
                    }
                }

                // Grab data from Old Who List.txt into List and merges the two lists together
                var logFile = File.ReadAllLines(@"C:\Users\User\Documents\Visual Studio 2019\Projects\WpfApp1\WpfApp1\bin\Debug\OldWhoList.txt");
                var OldWhoList = new List<string>(logFile);

                foreach (String s in WhoList)
                    if (OldWhoList.Contains(s))
                    { }
                    else
                    {
                        TextBlock1.Inlines.Add(s + " logged in at " + DateTime.Now + Environment.NewLine);
                    }

                foreach (String s in OldWhoList)
                    if (WhoList.Contains(s))
                    { }
                    else
                    {
                        TextBlock1.Inlines.Add(s + " logged out at " + DateTime.Now + Environment.NewLine);
                    }

                // Save current wholist to old wholist text
                TextWriter tw = new StreamWriter("OldWhoList.txt");
                foreach (String s in WhoList)
                    tw.WriteLine(s);
                tw.Close();


            }
        }
    }
}

I've tried creating a new method with the code separate from the button but I get an error that doesn't allow me to update the TextBlock.我尝试使用与按钮分开的代码创建一个新方法,但我收到一个错误,不允许我更新 TextBlock。

I just want to be able to execute Button_Click from inside the timer.我只想能够从计时器内部执行 Button_Click 。

You can't hook up a RoutedEventHandler directly to the Elapsed event of a System.Timers.Timer as it expects an ElapsedEventHandler .您不能将RoutedEventHandler直接连接到System.Timers.TimerElapsed事件,因为它需要ElapsedEventHandler You may call your Click event handler from an ElapsedEventHandler though:您可以从ElapsedEventHandler调用Click事件处理程序:

aTimer.Elapsed += (ss,ee) => Button_Click(this, new RoutedEventArgs());

You should use a DispatcherTimer here though since your event handler accesses UI elements.不过,您应该在此处使用DispatcherTimer ,因为您的事件处理程序会访问 UI 元素。 It has a Tick event:它有一个Tick事件:

aTimer.Tick += (ss, ee) => Button_Click(this, new RoutedEventArgs());

A System.Timers.Timer fires its Elapsed event on a background thread which will throw an InvalidOperationException when you try add inlines to the TextBlock in your event handler. System.Timers.Timer在后台线程上触发其Elapsed事件,当您尝试将内联添加到事件处理程序中的TextBlock时,该事件将引发InvalidOperationException

Instead of calling the Button_Click event handler from the Tick event handler, you should consider creating a method that performs the download and call this from both event handlers.而不是从Tick事件处理程序调用Button_Click事件处理程序,您应该考虑创建一个执行下载的方法并从两个事件处理程序调用它。

You should also look into the System.Net.HttpClient class and its async API.您还应该查看System.Net.HttpClient class 及其异步 API。

No overload for 'Button_Click' matches delegate 'ElapsedEventHandler'

Means that signature for ElapsedEventHandler is void (Object sender, ElapsedEventArgs e) .意味着 ElapsedEventHandler 的签名是void (Object sender, ElapsedEventArgs e) I see RoutedEventArgs insteadof ElapsedEventArgs .我看到RoutedEventArgs而不是ElapsedEventArgs Maybe the method address is wrong placed.可能方法地址放错了。 Button.Click signature is different to Timer.Elapsed Button.Click签名与Timer.Elapsed不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM