Hello, I'm following along Riemer's tutorial for terrain generation and I have my program working, but about 15 seconds after running the program, I get a an error that says,

"Win32 Exception was unhandled.

The operation completed successfully"

Here is my code.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace FlyingGame
{
    public class FlyingGame : Microsoft.Xna.Framework.Game
    {
		public static Color BACKGROUND_COLOR = Color.Black;
		public static Color WIREFRAME_COLOR = Color.White;
		public static Color FONT_COLOR = Color.YellowGreen;
		public const bool DEBUG_FONT = true;

        GraphicsDeviceManager graphics;
        GraphicsDevice device;
        Effect effect;
        Matrix viewMatrix, projectionMatrix, worldMatrix, posAndDirection;
        KeyboardState keyboard;
		MouseState mouse;
		Terrain terrain;
		VertexDeclaration vertDeclaration;
		SpriteBatch spriteBatch;
		SpriteFont spriteFont;

		// Camera variables.
		Vector3 cameraPos, cameraTarget;
		float aheadPos = 0.0f, lateralPos = 0.0f, previousScrollValue = 0.0f, height = 0.0f;
		

		static protected float[,] heightData;
		static protected VertexPositionColor[] vertices;
		static protected Texture2D heightMap;
		static protected int[] indices;


        public FlyingGame()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
			// Create a link directly to the GPU.
			device = graphics.GraphicsDevice;

            graphics.PreferredBackBufferWidth = GraphicsDevice.DisplayMode.Width - 10;
            graphics.PreferredBackBufferHeight = GraphicsDevice.DisplayMode.Height - 10;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();
            this.IsMouseVisible = true;

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
			//spriteBatch = new SpriteBatch(GraphicsDevice);
			spriteFont = Content.Load<SpriteFont>("font");

            // Load the effects file.
            effect = Content.Load<Effect>("effects");

			// Create terrain.
			heightMap = Content.Load<Texture2D>("heightmap");
			terrain = new Terrain(graphics, device);
			vertDeclaration = new VertexDeclaration(device, VertexPositionColor.VertexElements);

			// Sets up the camera.
			InitializeCamera();
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
        }

        protected override void Update(GameTime gameTime)
        {
			terrain = new Terrain(graphics, device);
			keyboard = Keyboard.GetState();

            // Allows the game to exit.
            if (keyboard.IsKeyDown(Keys.Escape))
                this.Exit();

            // Moves the camera based on input from the keyboard.
			aheadPos = lateralPos = 0;
			if(keyboard.IsKeyDown(Keys.W))
				aheadPos += 2f;
			if (keyboard.IsKeyDown(Keys.S))
				aheadPos -= 2f;
			if (keyboard.IsKeyDown(Keys.A))
				lateralPos += 2f;
			if (keyboard.IsKeyDown(Keys.D))
				lateralPos -= 2f;

            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(BACKGROUND_COLOR);
			device.RenderState.FillMode = FillMode.WireFrame;

            // TURN THIS ON FOR FINAL PRODUCT!!!
            device.RenderState.CullMode = CullMode.None;

            // Implement the effects file.
            effect.CurrentTechnique = effect.Techniques["Colored"];
            effect.Begin();

			AdjustCamera();

			///////////////////
			VertexPositionColor[] triangle = new VertexPositionColor[3];
			triangle[0] = new VertexPositionColor(new Vector3(0, 0, 0), Color.Red);
			triangle[1] = new VertexPositionColor(new Vector3(10, 0, 0), Color.Blue);
			triangle[2] = new VertexPositionColor(new Vector3(0, 0, 10), Color.Green);
			///////////////////

            // Iterate each pass in the effect.
            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Begin();
                device.VertexDeclaration = vertDeclaration;
				device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, vertices, 0, vertices.Length,
					indices, 0, indices.Length / 3);

				//////////////
				device.RenderState.FillMode = FillMode.Solid;
				device.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleFan, triangle, 0, 1);
				//////////////
                pass.End();
            }

            // End the effect.
			effect.End();

			if(DEBUG_FONT)
				DrawText();

            base.Draw(gameTime);
        }

        private void AdjustCamera()
        {
			// Adjusts camera orientation settings.
			cameraPos = Vector3.Add(cameraPos, new Vector3(lateralPos, height, aheadPos));
			cameraTarget = new Vector3(cameraPos.X, 10, cameraPos.Z - 1);
			viewMatrix = Matrix.CreateLookAt(cameraPos, cameraTarget, posAndDirection.Up);
			posAndDirection = Matrix.Invert(viewMatrix);

			effect.Parameters["xView"].SetValue(viewMatrix);
			effect.Parameters["xProjection"].SetValue(projectionMatrix);
			effect.Parameters["xWorld"].SetValue(worldMatrix);
        }

		private void DrawText()
		{
			device.RenderState.FillMode = FillMode.Solid;

			spriteBatch = new SpriteBatch(device);
			spriteBatch.Begin();

			spriteBatch.DrawString(spriteFont, "Camera position: \nx= " + cameraPos.X + "\ny= " + cameraPos.Y + "\nz= " + cameraPos.Z,
				new Vector2(20, 10), FONT_COLOR);
			spriteBatch.DrawString(spriteFont, "Camera target: \nx= " + cameraTarget.X + "\ny= " + cameraTarget.Y + "\nz= " + cameraTarget.Z,
				new Vector2(20, 200), FONT_COLOR);

			spriteBatch.End();
		}

		private void InitializeCamera()
		{
			cameraPos = new Vector3(0, 50, 0);
			cameraTarget = Vector3.Zero;
			Vector3 cameraUpVector;
			cameraUpVector = new Vector3(0, 0, 1);
			viewMatrix = Matrix.CreateLookAt(cameraPos, cameraTarget, cameraUpVector);
			projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver2, device.Viewport.AspectRatio, 1.0f, 3000.0f);
			worldMatrix = Matrix.CreateTranslation(-terrain.Width / 1.0f, 0, terrain.Height / 1.0f);

			posAndDirection = Matrix.Invert(viewMatrix);
		}
    }
}

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace FlyingGame
{
	public class Terrain : FlyingGame
	{
		GraphicsDevice device;
		GraphicsDeviceManager graphics;
		float minHeight, maxHeight;
		int width, height;

		public int Width
		{
			get { return width; }
			set { width = value; }
		}

		public int Height
		{
			get { return height; }
			set { height = value; }
		}

		public Terrain(GraphicsDeviceManager graphics, GraphicsDevice device)
		{
			this.graphics = graphics;
			this.device = device;

			LoadHeightData();
			SetUpVertices();
		}
		
		public void LoadHeightData()
		{
			width = heightMap.Width;
			height = heightMap.Height;

			Color[] heightMapColors = new Color[width * height];
			heightMap.GetData(heightMapColors);

			heightData = new float[width, height];
			for (int x = 0; x < width; x++)
				for (int y = 0; y < height; y++)
					heightData[x, y] = heightMapColors[x + y * width].R / 5.0f;
		}

		public void SetUpVertices()
		{
			DetermineMinAndMaxHeight();

			vertices = new VertexPositionColor[width * height];
			for (int x = 0; x < width; x++)
			{
				for (int y = 0; y < height; y++)
				{
					vertices[x + y * width].Position = new Vector3(x, heightData[x, y], -y);
					if (heightData[x, y] < minHeight + (maxHeight - minHeight) / 4)
						vertices[x + y * Width].Color = Color.Blue;
					else if (heightData[x, y] < minHeight + (maxHeight - minHeight) * 2 / 4)
						vertices[x + y * Width].Color = Color.Green;
					else if (heightData[x, y] < minHeight + (maxHeight - minHeight) * 3 / 4)
						vertices[x + y * Width].Color = Color.Brown;
					else
						vertices[x + y * Width].Color = Color.White;
				}
			}

			indices = new int[(width - 1) * (height - 1) * 6];
			int counter = 0;
			for (int y = 0; y < height - 1; y++)
			{
				for (int x = 0; x < width - 1; x++)
				{
					int lowerLeft = x + y * width;
					int lowerRight = (x + 1) + y * width;
					int topLeft = x + (y + 1) * width;
					int topRight = (x + 1) + (y + 1) * width;

					indices[counter++] = topLeft;
					indices[counter++] = lowerRight;
					indices[counter++] = lowerLeft;

					indices[counter++] = topLeft;
					indices[counter++] = topRight;
					indices[counter++] = lowerRight;
				}
			}
		}

		private void DetermineMinAndMaxHeight()
		{
			minHeight = float.MaxValue;
			maxHeight = float.MinValue;

			for (int x = 0; x < Width; x++)
			{
				for (int y = 0; y < Height; y++)
				{
					if (heightData[x, y] < minHeight)
						minHeight = heightData[x, y];
					if (heightData[x, y] > maxHeight)
						maxHeight = heightData[x, y];
				}
			}
		}
	}
}

Any ideas as to what is causing the Win32 error? I have no idea what that indicates. Thanks for your help.

What I might try in this case is running the application in debug mode and trying to actually capture more specific information about the error from the debug/output consoles (assuming you're using an IDE for development).

A more specific error message might help both you and the community to figure out specifically what the cause is :)

Okay, this is what info I could glean from it:


System.ComponentModel.Win32Exception was unhandled
Message="The operation completed successfully"
Source="System.Drawing"
ErrorCode=-2147467259
NativeErrorCode=0
StackTrace:
at System.Drawing.Icon.Initialize(Int32 width, Int32 height)
at System.Drawing.Icon..ctor(Type type, String resource)
at Microsoft.Xna.Framework.WindowsGameWindow.GetDefaultIcon()
at Microsoft.Xna.Framework.WindowsGameWindow..ctor()
at Microsoft.Xna.Framework.WindowsGameHost..ctor(Game game)
at Microsoft.Xna.Framework.Game.EnsureHost()
at Microsoft.Xna.Framework.Game..ctor()
at FlyingGame.FlyingGame..ctor() in C:\Users\User\Documents\Visual Studio 2008\Projects\FlyingGame\FlyingGame\FlyingGame.cs:line 73
at FlyingGame.Terrain..ctor(GraphicsDeviceManager graphics, GraphicsDevice device) in C:\Users\User\Documents\Visual Studio 2008\Projects\FlyingGame\FlyingGame\Terrain.cs:line 29
at FlyingGame.FlyingGame.Update(GameTime gameTime) in C:\Users\User\Documents\Visual Studio 2008\Projects\FlyingGame\FlyingGame\FlyingGame.cs:line 138
at Microsoft.Xna.Framework.Game.Tick()
at Microsoft.Xna.Framework.Game.HostIdle(Object sender, EventArgs e)
at Microsoft.Xna.Framework.GameHost.OnIdle()
at Microsoft.Xna.Framework.WindowsGameHost.ApplicationIdle(Object sender, EventArgs e)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle(Int32 grfidlef)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Microsoft.Xna.Framework.WindowsGameHost.Run()
at Microsoft.Xna.Framework.Game.Run()
at FlyingGame.Program.Main(String[] args) in C:\Users\User\Documents\Visual Studio 2008\Projects\FlyingGame\FlyingGame\Program.cs:line 14
at System.AppDomain._nExecuteAssembly(Assembly 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.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

Does this help?

The ErrorCode=-2147467259 = 0x80004005 means "Unspecified Error" - Not much help.:(

"...at System.Drawing.Icon.Initialize(Int32 width, Int32 height)
at System.Drawing.Icon..ctor(Type type, String resource)
at Microsoft.Xna.Framework.WindowsGameWindow.GetDefaultIcon()..."
This bit of the error message would suggest that the problem is to do with the default Icon. :?:

Have you configured a default Icon?

Actually, my last post is a red herring. Ignore it.
This is the bit that shows where the error is.

... at FlyingGame.Terrain..ctor(GraphicsDeviceManager graphics, GraphicsDevice device) in C:\Users\User\Documents\Visual Studio 2008\Projects\FlyingGame\FlyingGame\Terrain.cs:line 29
at FlyingGame.FlyingGame.Update(GameTime gameTime) in C:\Users\User\Documents\Visual Studio 2008\Projects\FlyingGame\FlyingGame\FlyingGame.cs:line 138 ...

This indicates that in the Update method you are trying to construct a new game object.

protected override void Update(GameTime gameTime)
{
    terrain = new Terrain(graphics, device); //<-- This is where the error occurs.
    keyboard = Keyboard.GetState();
    ...

Are you sure you need to create a new FlyingGame object in the Update of your FlyingGame object?

Hmm, so is it because class Terrain is derived from class FlyingGame?

Oh yeah! I already loaded that class. I don't know why I put that in the Update method. Stupid me. *Facepalm* Thanks for your help.

@nick.crane
I wanted to let you know that after trying a couple other solutions to the

"Win32 Exception was unhandled.
The operation completed successfully"

your solution was the one that worked for me, very much appreciated.
Aparently I was attempting to do pretty much the same thing; creating a new instance of a class each update... the sad part was that it was leftover code that I had forgotten about so thankfully it wasn't actually being used and all I had to do was delete it.

This article has been dead for over six months. Start a new discussion instead.