首页 > 解决方案 > 如何使用按钮更改图像框 | c# windows 窗体

问题描述


我想使用按钮将图像从第一张更改为第二张。启动表单时,应始终加载第一张图像,按下按钮后图像与第二张交换,反之亦然。我怎么能这样做?
图片由 imgbox 加载,没有代码。所有图像都存储在一个名为资源的文件夹中。Form1.cs 代码:

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

namespace WindowsFormsApp4
{


    public partial class Form1 : Form
    {

        WindowsMediaPlayer player = new WindowsMediaPlayer();

        public Form1()
        {
            InitializeComponent();

            player.URL = "tada.mp3";
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            player.controls.play();
        }

        private void changebutton_Click(object sender, EventArgs e)
        {

        }

        private void Form1_HelpButtonClicked(Object sender, CancelEventArgs e)

        {

            MessageBox.Show("PZP - Przeglądarka zdjęć P0150Na", "Informacje", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}



真诚
的 p0150n

标签: c#imagebutton

解决方案


添加所有可能图像的数组。添加一个变量以将当前加载的图像索引存储在此数组中。并在 buttonClick 事件上,改变当前加载的图片索引,并将图片加载到图片框。有了这个想法,您可能有超过 2 张图像。像这样的东西:

public partial class Form1 : Form
{
    string[] images = new string[] { "image1.bmp", "image2.bmp", "image3.bmp" };
    int currentImageIndex = 0;

    ...
    private void changebutton_Click(object sender, EventArgs e)
    {
        currentImageIndex++;
        if (currentImageIndex == images.Length)
            currentImageIndex = 0;

        pictureBox.Image = Image.FromFile(images[currentImageIndex]));
    }
    ...
}

推荐阅读