c# 用图像显示intptr
时间: 2023-06-15 20:03:51 浏览: 113
在C#中,可以使用IntPtr类型来表示指针或句柄,例如表示图像的句柄。要使用IntPtr类型来显示图像,可以使用Windows API函数来获取图像句柄,然后使用Graphics类将其绘制到画布上。
下面是一个简单的示例代码,可以将IntPtr类型的图像句柄绘制到控件上:
```csharp
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ShowImageWithIntPtr
{
public partial class Form1 : Form
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr LoadImage(IntPtr hInst, string lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad);
private const uint IMAGE_BITMAP = 0;
private const uint LR_CREATEDIBSECTION = 0x00002000;
private IntPtr _imageHandle;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Load image handle
_imageHandle = LoadImage(IntPtr.Zero, "image.bmp", IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);
// Redraw the control
Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
// Create graphics object
Graphics g = e.Graphics;
// Get bitmap from handle
Bitmap bmp = Bitmap.FromHbitmap(_imageHandle);
// Draw bitmap
g.DrawImage(bmp, new Point(0, 0));
// Clean up
bmp.Dispose();
}
}
}
```
在这个示例中,LoadImage函数从文件中加载图像并返回一个IntPtr类型的句柄。然后,当控件需要绘制图像时,使用Graphics类将位图绘制到控件上。注意,必须在绘制完成后,调用Bitmap对象的Dispose方法来释放内存。