我剛剛開始使用C#,作爲一個項目,我決定嘗試製作一個圖像轉換器,但我似乎無法獲得在我的button1上下文中可訪問的變量「open」,我不尋找評論我的代碼有多糟糕,我剛剛開始......我只想完成它並添加到它,稍後我會改進代碼,謝謝。那我該如何讓它可以訪問?如何使OpenFileDialog變量Global?
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 System.IO;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button2_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
// image filters
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
// image in picture box
pictureBox1.Image = new Bitmap(open.FileName);
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
// image file path
string path = Directory.GetCurrentDirectory();
textBox1.Text = Path.GetDirectoryName(open.FileName);
}
}
public void Form1_Load(object sender, EventArgs e)
{
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
flowLayoutPanel1 = new FlowLayoutPanel();
flowLayoutPanel1.AutoSize = true;
flowLayoutPanel1.AutoSizeMode = AutoSizeMode.GrowAndShrink;
this.Controls.Add(flowLayoutPanel1);
}
public void button1_Click(object sender, EventArgs e)
{
int selectedIndex = comboBox1.SelectedIndex;
Object selectedItem = comboBox1.SelectedItem;
if ((string)comboBox1.SelectedItem == "*.jpg")
{
pictureBox1.Image.Save(@"" + textBox1.Text + open.FileName + "", System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}
介意你要請分享製作'開放的理念'可訪問?提問的理由是,看到你的代碼並不適合。該變量可以被聲明爲一個類變量或者你提供一個私有屬性;然而,'OpenFileDialog'是一個模態對話框並返回一個結果 - 你通常不想再次訪問變量,特別是不能從不同的上下文訪問變量。 – 2015-01-21 04:09:22