- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我希望我的游戏有正常的文本输入,但使用纯 XNA 似乎很不愉快。
早些时候我发现这段代码让我可以使用 MessageBox
在我的游戏周围,安全地暂停其执行并显示一条消息:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern uint MessageBox(IntPtr hWnd, String text, String caption, uint type);
InputBox
我的游戏的功能,最好不要中断(暂停)游戏?
最佳答案
啊,文本输入 - 我最近有这方面的经验。
问题
通常,Keyboard.GetKeyboardState()
获取文本输入很糟糕,这有很多原因,其中一些是:
OemPeriod
-like 键(如在测试中)以查看它们的实际位置,并将它们映射到特定值。 Game.Initialize()
中对其进行初始化。覆盖方法(通过使用 Game.Window),并连接到事件以在您想要的任何地方接收输入。
PresentationCore
(PresentationCore.dll) 到您的引用以使用此代码(需要
System.Windows.Input
命名空间)。这适用于 .NET 4.0 和 .NET 4.0 Client Profile。
using System;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Text;
using System.Windows.Input;
namespace EventInput
{
public class KeyboardLayout
{
const uint KLF_ACTIVATE = 1; //activate the layout
const int KL_NAMELENGTH = 9; // length of the keyboard buffer
const string LANG_EN_US = "00000409";
const string LANG_HE_IL = "0001101A";
[DllImport("user32.dll")]
private static extern long LoadKeyboardLayout(
string pwszKLID, // input locale identifier
uint Flags // input locale identifier options
);
[DllImport("user32.dll")]
private static extern long GetKeyboardLayoutName(
System.Text.StringBuilder pwszKLID //[out] string that receives the name of the locale identifier
);
public static string getName()
{
System.Text.StringBuilder name = new System.Text.StringBuilder(KL_NAMELENGTH);
GetKeyboardLayoutName(name);
return name.ToString();
}
}
public class CharacterEventArgs : EventArgs
{
private readonly char character;
private readonly int lParam;
public CharacterEventArgs(char character, int lParam)
{
this.character = character;
this.lParam = lParam;
}
public char Character
{
get { return character; }
}
public int Param
{
get { return lParam; }
}
public int RepeatCount
{
get { return lParam & 0xffff; }
}
public bool ExtendedKey
{
get { return (lParam & (1 << 24)) > 0; }
}
public bool AltPressed
{
get { return (lParam & (1 << 29)) > 0; }
}
public bool PreviousState
{
get { return (lParam & (1 << 30)) > 0; }
}
public bool TransitionState
{
get { return (lParam & (1 << 31)) > 0; }
}
}
public class KeyEventArgs : EventArgs
{
private Keys keyCode;
public KeyEventArgs(Keys keyCode)
{
this.keyCode = keyCode;
}
public Keys KeyCode
{
get { return keyCode; }
}
}
public delegate void CharEnteredHandler(object sender, CharacterEventArgs e);
public delegate void KeyEventHandler(object sender, KeyEventArgs e);
public static class EventInput
{
/// <summary>
/// Event raised when a character has been entered.
/// </summary>
public static event CharEnteredHandler CharEntered;
/// <summary>
/// Event raised when a key has been pressed down. May fire multiple times due to keyboard repeat.
/// </summary>
public static event KeyEventHandler KeyDown;
/// <summary>
/// Event raised when a key has been released.
/// </summary>
public static event KeyEventHandler KeyUp;
delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
static bool initialized;
static IntPtr prevWndProc;
static WndProc hookProcDelegate;
static IntPtr hIMC;
//various Win32 constants that we need
const int GWL_WNDPROC = -4;
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
const int WM_CHAR = 0x102;
const int WM_IME_SETCONTEXT = 0x0281;
const int WM_INPUTLANGCHANGE = 0x51;
const int WM_GETDLGCODE = 0x87;
const int WM_IME_COMPOSITION = 0x10f;
const int DLGC_WANTALLKEYS = 4;
//Win32 functions that we're using
[DllImport("Imm32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("Imm32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
/// <summary>
/// Initialize the TextInput with the given GameWindow.
/// </summary>
/// <param name="window">The XNA window to which text input should be linked.</param>
public static void Initialize(GameWindow window)
{
if (initialized)
throw new InvalidOperationException("TextInput.Initialize can only be called once!");
hookProcDelegate = new WndProc(HookProc);
prevWndProc = (IntPtr)SetWindowLong(window.Handle, GWL_WNDPROC,
(int)Marshal.GetFunctionPointerForDelegate(hookProcDelegate));
hIMC = ImmGetContext(window.Handle);
initialized = true;
}
static IntPtr HookProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
IntPtr returnCode = CallWindowProc(prevWndProc, hWnd, msg, wParam, lParam);
switch (msg)
{
case WM_GETDLGCODE:
returnCode = (IntPtr)(returnCode.ToInt32() | DLGC_WANTALLKEYS);
break;
case WM_KEYDOWN:
if (KeyDown != null)
KeyDown(null, new KeyEventArgs((Keys)wParam));
break;
case WM_KEYUP:
if (KeyUp != null)
KeyUp(null, new KeyEventArgs((Keys)wParam));
break;
case WM_CHAR:
if (CharEntered != null)
CharEntered(null, new CharacterEventArgs((char)wParam, lParam.ToInt32()));
break;
case WM_IME_SETCONTEXT:
if (wParam.ToInt32() == 1)
ImmAssociateContext(hWnd, hIMC);
break;
case WM_INPUTLANGCHANGE:
ImmAssociateContext(hWnd, hIMC);
returnCode = (IntPtr)1;
break;
}
return returnCode;
}
}
}
EventInput.CharEntered
事件),并使用逻辑来检测将输入发送到何处。
KeyboardDispatcher
,它通过具有类型
IKeyboardSubscriber
的属性来处理键盘输入的调度。它向其发送接收到的输入。这个想法是您将此属性设置为要接收输入的 UI 控件。
public interface IKeyboardSubscriber
{
void RecieveTextInput(char inputChar);
void RecieveTextInput(string text);
void RecieveCommandInput(char command);
void RecieveSpecialInput(Keys key);
bool Selected { get; set; } //or Focused
}
public class KeyboardDispatcher
{
public KeyboardDispatcher(GameWindow window)
{
EventInput.EventInput.Initialize(window);
EventInput.EventInput.CharEntered += new EventInput.CharEnteredHandler(EventInput_CharEntered);
EventInput.EventInput.KeyDown += new EventInput.KeyEventHandler(EventInput_KeyDown);
}
void EventInput_KeyDown(object sender, EventInput.KeyEventArgs e)
{
if (_subscriber == null)
return;
_subscriber.RecieveSpecialInput(e.KeyCode);
}
void EventInput_CharEntered(object sender, EventInput.CharacterEventArgs e)
{
if (_subscriber == null)
return;
if (char.IsControl(e.Character))
{
//ctrl-v
if (e.Character == 0x16)
{
//XNA runs in Multiple Thread Apartment state, which cannot recieve clipboard
Thread thread = new Thread(PasteThread);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
_subscriber.RecieveTextInput(_pasteResult);
}
else
{
_subscriber.RecieveCommandInput(e.Character);
}
}
else
{
_subscriber.RecieveTextInput(e.Character);
}
}
IKeyboardSubscriber _subscriber;
public IKeyboardSubscriber Subscriber
{
get { return _subscriber; }
set
{
if (_subscriber != null)
_subscriber.Selected = false;
_subscriber = value;
if(value!=null)
value.Selected = true;
}
}
//Thread has to be in Single Thread Apartment state in order to receive clipboard
string _pasteResult = "";
[STAThread]
void PasteThread()
{
if (Clipboard.ContainsText())
{
_pasteResult = Clipboard.GetText();
}
else
{
_pasteResult = "";
}
}
}
KeyboardDispatcher
,即在
Game.Initialize()
并保留对它的引用(以便您可以在选定的 [focused] 控件之间切换),并将使用
IKeyboardSubscriber
的类传递给它界面,例如您的
TextBox
.
public delegate void TextBoxEvent(TextBox sender);
public class TextBox : IKeyboardSubscriber
{
Texture2D _textBoxTexture;
Texture2D _caretTexture;
SpriteFont _font;
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; private set; }
public bool Highlighted { get; set; }
public bool PasswordBox { get; set; }
public event TextBoxEvent Clicked;
string _text = "";
public String Text
{
get
{
return _text;
}
set
{
_text = value;
if (_text == null)
_text = "";
if (_text != "")
{
//if you attempt to display a character that is not in your font
//you will get an exception, so we filter the characters
//remove the filtering if you're using a default character in your spritefont
String filtered = "";
foreach (char c in value)
{
if (_font.Characters.Contains(c))
filtered += c;
}
_text = filtered;
while (_font.MeasureString(_text).X > Width)
{
//to ensure that text cannot be larger than the box
_text = _text.Substring(0, _text.Length - 1);
}
}
}
}
public TextBox(Texture2D textBoxTexture, Texture2D caretTexture, SpriteFont font)
{
_textBoxTexture = textBoxTexture;
_caretTexture = caretTexture;
_font = font;
_previousMouse = Mouse.GetState();
}
MouseState _previousMouse;
public void Update(GameTime gameTime)
{
MouseState mouse = Mouse.GetState();
Point mousePoint = new Point(mouse.X, mouse.Y);
Rectangle position = new Rectangle(X, Y, Width, Height);
if (position.Contains(mousePoint))
{
Highlighted = true;
if (_previousMouse.LeftButton == ButtonState.Released && mouse.LeftButton == ButtonState.Pressed)
{
if (Clicked != null)
Clicked(this);
}
}
else
{
Highlighted = false;
}
}
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
bool caretVisible = true;
if ((gameTime.TotalGameTime.TotalMilliseconds % 1000) < 500)
caretVisible = false;
else
caretVisible = true;
String toDraw = Text;
if (PasswordBox)
{
toDraw = "";
for (int i = 0; i < Text.Length; i++)
toDraw += (char) 0x2022; //bullet character (make sure you include it in the font!!!!)
}
//my texture was split vertically in 2 parts, upper was unhighlighted, lower was highlighted version of the box
spriteBatch.Draw(_textBoxTexture, new Rectangle(X, Y, Width, Height), new Rectangle(0, Highlighted ? (_textBoxTexture.Height / 2) : 0, _textBoxTexture.Width, _textBoxTexture.Height / 2), Color.White);
Vector2 size = _font.MeasureString(toDraw);
if (caretVisible && Selected)
spriteBatch.Draw(_caretTexture, new Vector2(X + (int)size.X + 2, Y + 2), Color.White); //my caret texture was a simple vertical line, 4 pixels smaller than font size.Y
//shadow first, then the actual text
spriteBatch.DrawString(_font, toDraw, new Vector2(X, Y) + Vector2.One, Color.Black);
spriteBatch.DrawString(_font, toDraw, new Vector2(X, Y), Color.White);
}
public void RecieveTextInput(char inputChar)
{
Text = Text + inputChar;
}
public void RecieveTextInput(string text)
{
Text = Text + text;
}
public void RecieveCommandInput(char command)
{
switch (command)
{
case '\b': //backspace
if (Text.Length > 0)
Text = Text.Substring(0, Text.Length - 1);
break;
case '\r': //return
if (OnEnterPressed != null)
OnEnterPressed(this);
break;
case '\t': //tab
if (OnTabPressed != null)
OnTabPressed(this);
break;
default:
break;
}
}
public void RecieveSpecialInput(Keys key)
{
}
public event TextBoxEvent OnEnterPressed;
public event TextBoxEvent OnTabPressed;
public bool Selected
{
get;
set;
}
}
TextBox
时,别忘了设置
X
,
Y
, 和
Width
(!!!) 实例上的值(
Height
由字体自动设置)。
.Draw()
实例上的方法(在您的
Game.Draw()
方法中),spritebatch 已经启动(
SpriteBatch.Begin()
被调用!!!)。对于您显示的每个框,如果您希望它接收鼠标输入,您应该调用
.Update()
方法。
KeyboardDispatcher
订阅它的实例,例如:
_keyboardDispatcher.Subscriber = _usernameTextBox;
Click
,
Tab
和
Enter
文本框上的事件以切换订阅者(我推荐这样做,因为当您可以通过选项卡浏览它并单击以选择时,它会给 UI 带来非常好的感觉)。
关于c# - 向 XNA 游戏添加类似输入框的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10216757/
我想实现自定义搜索,但遇到了一个麻烦。我需要将 UIButton、SearchBar 组合在一个控件中,以便我可以通过指针引用它。然后我将向该组合控件动态添加更多 UIbutton。最重要的是,我想将
它没有在我的方法中执行 if block 中的语句 母版页:- 页面加载事件:- Control c = new Control(); DoSomething(c); 我的方法:- protecte
ComboBox 控件有一个 setConverter 方法,请参阅 JavaFX ComboBox - Display text but return ID on selection举个例子。我正在
我没有找到任何包含用于标记化(标记)文本输入的控件的 wpf 库。也许我找不到库,因为我错误地调用了这个组件。怎么叫或者哪里有这样的库? 最佳答案 DevExpress WPF 库包含多个数据编辑控件
是否有 Silverlight 控件允许您输入文本并将其突出显示为代码? 例如: foreach (client in Clients){ client.Save();} would become
我有以下用户控件 a) Panel.ZIndex="99999999" 是否是将此控件设置为该控件中 TopMost 的正
是否可以在 Windows 窗体中使用 C# 在窗体加载时隐藏所有特定控件,例如标签或按钮,然后选择显示我不想显示的那些? 我有一个包含很多按钮和标签的程序,但我只想在加载时显示一两个,我觉得对每个标
这个问题已经有答案了: 已关闭11 年前。 Possible Duplicate: Duplicating components at Run-Time 我有一个TMyControl ( Contro
我正在尝试在 Delphi 中编写一个 dll 库,其中包含一个创建 TFrame 后代实例并返回它的函数。但是当我在应用程序中导入这个函数时,每次调用它时,我都会得到一个异常,例如“'xxx'控件没
是否有 Win32 API 调用来确定哪些窗口和/或控件在特定坐标和/或鼠标下可见? 最佳答案 您可以使用GetWindowFromPoint 。它将返回窗口句柄,以便您可以使用 GetClassNa
我需要在编辑控件中输入以下公式: 公式是在 MS Word 中制作的。尝试将其复制/粘贴到编辑控件(单行或多行)后,我得到 M 0.33 Q10T9.1-9.7。 当我输入这个时,我正在研究 Rich
我只是想成功地将它添加到我的窗口中,但这却出奇地困难。 我已经尝试过 #include "windef.h" #include "winbase.h" #include "initguid.h" #i
我希望能够使用 google maps api v3 拥有自己的“街景”按钮。单击按钮时,我希望它根据我的标记经纬度加载街景。然后我希望按钮更改为“返回 map ”,然后再次加载默认 map View
我目前正在用 PHP 开发(另一个)开源 CMS,我想使用 javascript 控件,尤其是管理面板。问题是,是否有任何具有 PHP 接口(interface)的开源、可自由分发的控件(用于创建 j
我为其编写软件的产品之一是会计类应用程序。它用 C++ 编写,使用 C++ Builder 和 VCL 控件,连接到运行在 Linux 上的 PostgreSQL 数据库。 PostgreSQL 数据
我使用 Key Listener 来读取用户的输入,但我遇到了问题。首先,我读到 JTextField“请输入您的姓名”。如果用户输入一个名字,例如 John,它将更改为 John。但是,如果用户输入
我正在尝试对齐数据表列中的复选框(h=center,v=middle) ... 但复选框仍然显示在错误的位置(见附图)
我有一个包含统计信息的 JSON 数据树: { prefix: "a", count: 20, children: [ { prefix: "a:b", c
我在 Photoshop 中设计了一个模型,我打算将它应用到我的产品目录的 ListView 控件中,但它似乎没有正确显示(未对齐?),我希望这里的人可以像我一样指出我的错误试图弄清楚无济于事。 预期
您是使用 ASP.NET 控件还是仅使用带有 CSS 的 HTML? 我在 TextBox 和 DropDownList 的宽度方面遇到了一些问题。在不同的浏览器中,宽度会有所不同,控件的大小也不会相
我是一名优秀的程序员,十分优秀!