我正在创建一个控制台应用程序游戏,我想在屏幕上显示一些图像。因此,我在Google上找到了一些技巧,并创建了该脚本来显示图像:
[DllImport("user32.dll")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", SetLastError = true)] public static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("kernel32.dll", EntryPoint = "GetConsoleWindow", SetLastError = true)] private static extern IntPtr GetConsoleHandle();
private static void ShowImage(string filePath, int posX, int posY)
{
Image img = Image.FromFile(filePath);
var form = new Form
{
FormBorderStyle = FormBorderStyle.None
};
var parent = GetConsoleHandle();
var child = form.Handle;
SetParent(child, parent);
MoveWindow(child, 50, 50, img.Width, img.Height, true);
form.Paint += delegate (object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
Rectangle rc = new Rectangle(new Point(0, 0), img.Size);
g.DrawImage(img, form.ClientRectangle, rc, GraphicsUnit.Pixel);
};
Application.Run(form);
}
我的问题是,有时我不知道为什么,我的图像没有出现!而且它是随机的,不是2或1之类的1次!
注意:我使用此代码显示 png 图片
所以,如果有人知道是问题所在,我准备记笔记了:)