【问题标题】:how to change imagebox with a button | c# windows forms如何使用按钮更改图像框 | c# windows 窗体
【发布时间】:2020-07-22 04:12:57
【问题描述】:


我想使用按钮将图像从第一张更改为第二张。启动我的表单时,应始终加载第一张图像,按下按钮后图像与第二张交换,反之亦然。我怎么能这样做?
图片由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

【问题讨论】:

  • 您是否为您的按钮添加了点击处理程序?
  • 是的,我做到了。我不知道下一步该做什么。
  • 请提供您的代码sn-p。
  • private void changebutton_Click(object sender, EventArgs e) { } 命名空间中的其余内容是用于单击帮助按钮并在启动时播放声音的代码。没有错误或警告。
  • 请通过单击编辑在您的帖子中包含您的事件处理程序代码...我们将对您用于更改图像的逻辑感兴趣...您评论中的代码没有t 实际上做任何事情......所以我们需要查看您的其余代码。即:您如何显示默认图像以及其他图像的存储位置。

标签: c# image button


【解决方案1】:

添加所有可能图像的数组。添加一个变量以将当前加载的图像索引存储在此数组中。并在 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]));
    }
    ...
}

【讨论】:

  • 由于 vars,我得到了两个 CS0825 错误。你确定我应该把那个代码放在那个地方吗?
  • 我把它改成了 string[] 和 int。
  • 现在我收到一个 CS0029 错误,我无法将字符串转换为 System.Drawing.Image。
  • 查看我的新编辑。代码是用记事本写的,可能会有一些错误。
  • 我在没有第二个的情况下启动了表单)因为我收到两个错误说 } 和 ;预料之中。如果没有您为我编写的代码,按钮不会执行任何操作。
【解决方案2】:

VDN,当我在public Form1() 中编码changebutton.Click += new EventHandler(changebutton_Click); 时,当我单击按钮(如果重要的话,它被命名为“changebutton”)时,我的 IDE 向我显示了一个未处理的异常:System.IO.FileNotFoundException: „nerf.png ”。该文件是我要显示的第二张图片。

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多