如何在XNA游戏中获得I Beam游标?

时间:2010-06-27 23:50:58

标签: c# xna mouse-cursor

我已经设法让游戏更改为一个简单的XNA'游戏'中的IBeam,其中包含更新:

protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        if (Keyboard.GetState().IsKeyDown(Keys.A))
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Arrow;
        }
        if (Keyboard.GetState().IsKeyDown(Keys.I))
        {
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.IBeam;
        }

        base.Update(gameTime);
    }

按下“I”时,鼠标会切换到IBeam光标,但在移动鼠标时会立即更改为箭头。有没有办法让它保持默认的Windows IBeam,还是需要创建和跟踪自定义光标?

[编辑]我还应该指出,每一帧设置光标会导致鼠标移动时闪烁。似乎XNA(或Windows)在内部每次都将光标重置为箭头?

2 个答案:

答案 0 :(得分:2)

听起来你必须手动绘制它。它应该不会太难 - 只需在光标位置通过SpriteBatch绘制一个精灵。

// ex.
protected override void Draw(GameTime gameTime)
{
    // Other stuff...

    base.Draw(gameTime);

    // Retrieve mouse position
    MouseState mState = Mouse.GetState();
    Vector2 mousePos = new Vector2(mState.X, mState.Y);

    // Use this instead to optionally center the texture:
    // Vector2 mousePos = new Vector2(mState.X - cursorTexture.Width / 2, mState.Y - cursorTexture.Height / 2);

    // Draw cursor after base.Draw in order to draw it after any DrawableGameComponents.
    this.spriteBatch.Begin(); // Optionally save state
    this.spriteBatch.Draw(cursorTexture, mousePos, Color.White);
    this.spriteBatch.End();
}

这里有一些提取光标图像的代码。请记住,您需要额外引用System.Drawing。

protected override void LoadContent()
{
    // Other stuff...

    // The size of the cursor in pixels.
    int cursorSize = 32;

    // Draw the cursor to a Bitmap
    Cursor cursor = Cursors.IBeam;
    Bitmap image = new Bitmap(cursorSize, cursorSize);
    Graphics graphics = Graphics.FromImage(image);
    cursor.Draw(graphics, new Rectangle(0, 0, cursorSize, cursorSize));

    // Extract pixels from the bitmap, and copy into the texture.
    cursorTexture = new Texture2D(GraphicsDevice, cursorSize, cursorSize);
    Microsoft.Xna.Framework.Graphics.Color[] data = new Microsoft.Xna.Framework.Graphics.Color[cursorSize * cursorSize];
    for (int y = 0; y < cursorSize; y++)
    {
        for (int x = 0; x < cursorSize; x++)
        {
            System.Drawing.Color color = image.GetPixel(x, y);
            data[x + y * cursorSize] = new Microsoft.Xna.Framework.Graphics.Color(color.R, color.G, color.B, color.A);
        }
    }
    cursorTexture.SetData<Microsoft.Xna.Framework.Graphics.Color>(data);
}

请记住,这不是我的头脑 - 不能保证工作。不过,基本的想法就在那里。

答案 1 :(得分:2)

在手动绘制之前,我尝试设置底层System.Windows.Forms.Form的Cursor属性:

Form f = (Form)Control.FromHandle(Game.Window.Handle);
f.Cursor = System.Windows.Forms.Cursors.IBeam;

由于我现在没有安装XNA,我不知道这是否会起作用,或者它是否会持久,但我不明白为什么不会这样。