/*-->思路(仅供参考):先找到窗体的句柄(存放到mainHandle)-->再用SendMessage(mainHandle, 0x10, 0, 0);关闭窗体*/
using BCZG_WinFrom;
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BCZG_WinFrom
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 获取窗体的句柄函数
/// </summary>
/// <param name="lpClassName">窗口类名</param>
/// <param name="lpWindowName">窗口标题名</param>
/// <returns>返回句柄</returns>
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
/// <summary>
/// 设置窗体状态(0:隐藏窗体,1:默认窗体,2:最小化窗体,3:最大化窗体,....)
/// </summary>
/// <param name="hwnd">窗体句柄</param>
/// <param name="nCmdShow">状态</param>
/// <returns></returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
/// <summary>
///
/// </summary>
/// <param name="hwnd">窗体句柄</param>
/// <param name="wMsg">16进制0x10为关闭窗体</param>
/// <param name="wParam"></param>
/// <param name="lParam"></param>
/// <returns></returns>
[DllImport("user32.dll", EntryPoint = "SendMessageA")]
public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
IntPtr mainHandle = IntPtr.Zero;
private void button1_Click(object sender, EventArgs e)
{
FormEg EgFrm1 = new FormEg();
EgFrm1.Text = "测试窗体";
EgFrm1.Show();
}
/// <summary>
/// 隐藏窗体
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
// 获取查找窗体句柄(通过窗体标题名)
mainHandle = FindWindow(null, "测试窗体");
if (mainHandle != IntPtr.Zero)
{
Console.WriteLine("找到窗体");
//通过句柄设置当前窗体状态(0:隐藏窗体,1:默认窗体,2:最小化窗体,3:最大化窗体,....)
ShowWindow(mainHandle, 0);
}else
{
MessageBox.Show("没有找到!");
}
}
/// <summary>
/// 关闭窗体
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
if(mainHandle!=IntPtr.Zero)
SendMessage(mainHandle, 0x10, 0, 0);
else
{
MessageBox.Show("没有可关闭的窗体!");
}
}
}
}
[此贴子已经被作者于2019-1-6 21:30编辑过]