注:API函数GetForegroundWindow用来获得前台窗口的句柄,这里的“前台窗口”是指前台应用程序的活动窗口
类ForegroundWindow继承了框架提供的IWin32Window接口,并定义了一个静态的IWin32Window属性Instance,用来获得前台窗口的句柄。
public class ForegroundWindow : IWin32Window
{
private static ForegroundWindow _window = new ForegroundWindow();
private ForegroundWindow(){}
public static IWin32Window Instance
{
get { return _window; }
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
IntPtr IWin32Window.Handle
{
get
{
return GetForegroundWindow();
}
}
public class Example1
{
public void SaveFile(string str_filepath)
{
SaveFileDialog openfile=new SaveFileDialog();
openfile.Title="请输入RTF文件名";
openfile.Filter="word文档(*.rtf)|*.rtf";
openfile.FilterIndex=0;
openfile.ValidateNames=true;
openfile.InitialDirectory= str_filepath;
openfile.ShowDialog(ForegroundWindow.Instance);
}
}
博客介绍了使用C#获取前台窗口句柄的方法,通过类ForegroundWindow继承IWin32Window接口,利用API函数GetForegroundWindow实现。还给出了保存RTF文档的示例代码,使用SaveFileDialog对话框,指定文件类型为RTF。
1139

被折叠的 条评论
为什么被折叠?



