[英]Add Attributes to Form Class
我想在Visual Studio 2013的C#应用程序中更改消息框的位置。我找到了这篇文章:
http://www.codeproject.com/Tips/472294/Position-a-Windows-Forms-MessageBox-in-Csharp
它说:“在您的Form类中,添加这些DllImport属性。”
这实际上需要我做什么? 我去了System.Windows.Forms参考。 如果那是我需要添加的代码,那么我不知道需要在其中添加代码,因为有很多事情我不知道。
导入以下名称空间
using System.Runtime.InteropServices;
using System.Threading;
在类级别编写以下代码(如果您想了解有关重新使用这些方法的信息,请参考pinvoke
[DllImport("user32.dll")]
static extern IntPtr FindWindow(IntPtr classname, string title);
[DllImport("user32.dll")]
static extern void MoveWindow(IntPtr hwnd, int X, int Y,int nWidth, int nHeight, bool rePaint);
[DllImport("user32.dll")]
static extern bool GetWindowRect(IntPtr hwnd, out Rectangle rect);
编写FindAndMoveMsgBox
方法并在需要的地方调用
在这里我在Form1构造函数中调用了方法,下面是最终代码
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern IntPtr FindWindow(IntPtr classname, string title);
[DllImport("user32.dll")]
static extern void MoveWindow(IntPtr hwnd, int X, int Y,int nWidth, int nHeight, bool rePaint);
[DllImport("user32.dll")]
static extern bool GetWindowRect(IntPtr hwnd, out Rectangle rect);
public Form1()
{
InitializeComponent();
FindAndMoveMsgBox(0, 0, true, "Title");
MessageBox.Show("Message", "Title");
}
void FindAndMoveMsgBox(int x, int y, bool repaint, string title)
{
Thread thr = new Thread(() => // create a new thread
{
IntPtr msgBox = IntPtr.Zero;
// while there's no MessageBox, FindWindow returns IntPtr.Zero
while ((msgBox = FindWindow(IntPtr.Zero, title)) == IntPtr.Zero) ;
// after the while loop, msgBox is the handle of your MessageBox
Rectangle r = new Rectangle();
GetWindowRect(msgBox, out r); // Gets the rectangle of the message box
MoveWindow(msgBox /* handle of the message box */, x, y,
r.Width - r.X /* width of originally message box */,
r.Height - r.Y /* height of originally message box */,
repaint /* if true, the message box repaints */);
});
thr.Start(); // starts the thread
}
}
}
(请参见上面的答案-我在键入代码时张贴的:))“ DLLImport”的作用是使您可以从托管代码中调用非托管代码中的函数。 这称为平台调用服务(或PInvoke)
在使用PInvoke服务之前,我敦促您熟悉PInvoke及其工作方式。 PInvoke非常棒,我在操作系统操作(例如您发布的链接)中大量使用了它。
已过时,但仍然是很好的PInvoke教程: http : //msdn.microsoft.com/zh-cn/library/aa288468( v=vs.71) .aspx
回答这个问题:在Form.cs文件顶部添加这些代码行(在类参考中)
public partial class MyForm : Form
{
[DllImport("user32.dll")]
static extern IntPtr FindWindow(IntPtr classname, string title); // extern method: FindWindow
[DllImport("user32.dll")]
static extern void MoveWindow(IntPtr hwnd, int X, int Y,
int nWidth, int nHeight, bool rePaint); // extern method: MoveWindow
[DllImport("user32.dll")]
static extern bool GetWindowRect
(IntPtr hwnd, out Rectangle rect); // extern method: GetWindowRect
//ETC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.