0

我已经设法让光标在一个简单的 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)每帧都在内部将光标重置为箭头?

4

2 回答 2

3

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

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

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

于 2011-01-22T22:25:41.820 回答
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);
}

请记住,这不是我的想法 - 不能保证有效。不过,基本的想法就在那里。

于 2010-07-13T00:10:20.570 回答