如何使用鼠标单击事件上的图片框更改 Windows 窗体的 back.color?

How to change back.color of WindowsForm using a picture box on a mouseClick event?

我有一个简单的 windows 表单,我添加了一个图片框,我想将其用作我的应用程序的暗模式 on/off 开关。我已经为鼠标点击创建了一个事件,但它只能以一种方式工作:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WeatherApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // The below two lines are used to move my WindowsForm window
        private bool mouseDown;
        private Point lastlocation; 
        

        public void picDarkMode_MouseClick(object sender, MouseEventArgs e)
        {
            //var frmForm1 = new Form1();
            //frmForm1.BackColor = Color.Black;
            //var darkTheme = this.BackColor = System.Drawing.Color.DarkGray;

            this.BackColor = System.Drawing.Color.DarkGray;

            if (System.Drawing.Color.DarkGray == System.Drawing.Color.DarkGray)
            {
                this.BackColor = System.Drawing.Color.LightYellow;
            }
            else
            {
                this.BackColor = System.Drawing.Color.DarkGray;
            }
                        
            //this.BackColor = System.Drawing.Color.LightYellow;            
        }

我尝试使用 if 语句,但不明白为什么它不起作用...

你犯了两个错误。您在 if 语句之前将背景颜色设置为 DarkGray,因此它始终会给出相同的结果,并且您将 DarkGray 与 DarkGray 进行比较,而不是将表单背景颜色与 DarkGray 进行比较。所以... 去掉这一行:

this.BackColor = System.Drawing.Color.DarkGray;

并更改此:

if (System.Drawing.Color.DarkGray == System.Drawing.Color.DarkGray)

为此:

if (this.BackColor == System.Drawing.Color.DarkGray)

这是整个点击事件:

public void picDarkMode_MouseClick(object sender, MouseEventArgs e)
{
    if (this.BackColor == System.Drawing.Color.DarkGray)
    {
        this.BackColor = System.Drawing.Color.LightYellow;
    }
    else
    {
        this.BackColor = System.Drawing.Color.DarkGray;
    }
}