C#:是否可以在program.cs中从资源图像创建位图?

时间:2015-11-21 21:49:33

标签: c# bitmap

在我的应用程序中,我想创建一个位图来绘制,然后在多个表单上显示它。我需要集中协调位图的更新,所以我想基于计时器从MAIN做到这一点。在创建时,位图将重新调整为屏幕的完整大小。是否这种尝试调整大小会导致异常?

代码看起来很好,VS在我尝试调试之前不会抱怨,然后它会在创建位图的行上抛出“参数无效”异常。

我选择性地压缩了下面的代码:

using System;
using System.Windows.Forms;
using System.IO;
using System.Timers;
using System.Drawing;
using System.Reflection;

namespace MyProgram
{
  /// <summary>
  /// Class with program entry point.
  /// </summary>
  internal sealed class Program
  {
    /// <summary>
    /// Program entry point.
    /// </summary>
    /// 

    public struct Config {
        public int Guns;
        public int RedGunMin;
        public int RedGunMax;
        public int X;
        public int Y;
        public double PointRatio;
    }

    public static Config TC;

    public static int OffsetX = 0;
    public static int OffsetY = 0;
    public static int Offset = 0;
    public static int FirstPass = 0;

    public static int XC = 0;
    public static int YC = 0;

    public static int RedVal = 0;
    public static int GreenVal = 0;
    public static int BlueVal = 0;

    //Set up the random number seed
    public static Random rand = new Random();

    //Create a bitmap object (from the image in the resource file)
    //***** The following line of code (70) generates the error: *****
    public static System.Drawing.Bitmap myBitMap = new Bitmap(MyProgram.Resource1.Black600x600,Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y);

    private static System.Timers.Timer myTimer;

    [STAThread]
    private static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);


        if (args.Length > 0)
        {
            string firstArgument = args[0].ToLower().Trim();

            if (firstArgument == "/c")           // Configuration mode
            {
                // TODO
            }
            else //(firstArgument == "/s")      Full-screen mode, and default mode
            {
                //Read the config file
                string strDocFolder;
                TileConfig TC = new TileConfig();

                strDocFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                //Check to see if the INI file exists
                if (File.Exists(strDocFolder + "\\TileConfig.ini"))
                {
                    //Read the configuration out of the file
                    TextReader TR = new StreamReader(strDocFolder + "\\TileConfig.ini");

                    TC.Guns = Convert.ToInt32(TR.ReadLine());
                    TC.RedGunMin = Convert.ToInt32(TR.ReadLine());
                    TC.RedGunMax = Convert.ToInt32(TR.ReadLine());
                    TC.X = Convert.ToInt32(TR.ReadLine());
                    TC.Y = Convert.ToInt32(TR.ReadLine());
                    TC.PointRatio = Convert.ToDouble(TR.ReadLine());

                    TR.Dispose();
                }
                else
                {
                    //File does not exist, assign default values
                    TC.Guns = 3;
                    TC.RedGunMin = 0;
                    TC.RedGunMax = 255;
                    TC.X = 4;
                    TC.Y = 3;
                    TC.PointRatio = 0.10;
                }

                //Choose initial color
                RedVal = rand.Next(0, 255);

                ShowScreen();

                myTimer.Start();

                Application.Run();
            }
        }

    }

当我将异常细节复制到剪贴板时,这就是我得到的:

System.TypeInitializationException was unhandled
 HResult=-2146233036
 Message=The type initializer for 'MyProgram.Program' threw an exception.
 Source=MyProgram
 TypeName=MyProgram.Program
 StackTrace:
      at MyProgram.Program.Main(String[] args)
      at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
      at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
      at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
      at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
      at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
      at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
      at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.ArgumentException
     HResult=-2147024809
     Message=Parameter is not valid.
     Source=System.Drawing
     StackTrace:
          at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
          at System.Drawing.Bitmap..ctor(Image original, Int32 width, Int32 height)
          at MyProgram.Program..cctor() in C:\Users\Randy\Documents\SharpDevelop Projects\MyProgram\MyProgram\Program.cs:line 70
   InnerException: 

感谢您提供的任何帮助。你们是最伟大的,我非常感谢你们帮助人们的方式!

1 个答案:

答案 0 :(得分:2)

异常详细信息清楚地表明,当您传递坐标时,您正在调用期望Bitmapwidth的{​​{1}}构造函数 - heightScreen.PrimaryScreen.Bounds.X ,最可能是0,因此无效大小。

如果您打算创建一个屏幕尺寸的位图,请改用Screen.PrimaryScreen.Bounds.YScreen.PrimaryScreen.Bounds.Width。或接受Screen.PrimaryScreen.Bounds.Height并传递Size的{​​{3}}。

相关问题