无法在桌面上放置位图文件

本文关键字:置位 位图 文件 桌面 | 更新日期: 2023-09-27 18:13:23

我正在创建一个绘图应用程序,为此我需要为面板创建一个位图。我的问题是,当我得到桌面位置,它给我的错误"字段初始化器不能引用非静态字段、方法或属性'Form1 "。路径"

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 Paint_AppLication
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private bool mouse_down = false;
    //My Problem
    string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    private Bitmap bit = new Bitmap(path + "''" + "Bitmap.bmp");

    // Other Code Not my problem
    private Color col = Color.Black;
    private void panel1_MouseDown(object sender, MouseEventArgs e)
    {
        mouse_down = true;
    }
    private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
        mouse_down = false;
    }
    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
        toolStripStatusLabel1.Text = e.X + ", " + e.Y;
        if (mouse_down == true)
        { 
            panel1.BackgroundImage = bit;
            bit.SetPixel(e.X, e.Y, col);
        }
    }
    private void button1_Click(object sender, EventArgs e)
    {
        colorDialog1.ShowDialog();
        col = colorDialog1.Color;
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
 }
}

无法在桌面上放置位图文件

因为你的字段必须是静态的:

初始代码:

using System;
using System.Drawing;
internal class MyClass1
{
    private readonly string _path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    private Bitmap _bitmap = new Bitmap(_path + "''" + "Bitmap.bmp");
}
固定代码:

using System;
using System.IO;
internal class MyClass2
{
    private static readonly string _path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    private Bitmap _bitmap = new Bitmap(_path + "''" + "Bitmap.bmp");
}

更好的是,让System.IO.Path类构建路径:

不再需要静态字段

using System;
using System.Drawing;
using System.IO;
internal class MyClass3
{
    private Bitmap _bitmap =
        new Bitmap(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Bitmap.bmp"));
}