C# .net 怎样点窗口右上角“X”(叉)结束自己的程序时同时结束外部的一个程序呢?

来源:百度知道 编辑:UC知道 时间:2024/05/15 22:22:44
在自己做的退出按钮中已经实现了这个功能,但是点窗口右上角的叉时却结束不了外部程序,请教各位大侠有没有妙技

调用 API 函数 SendMessage 发送 WM_CLOSE 消息。

DllImport("User32.dll",EntryPoint="SendMessage")] private static extern int SendMessage( int hWnd,
int Msg,
int wParam,
int lParam);

const int WM_CLOSE = 0x10;
SendMessage(那个程序的窗口句柄, WM_CLOSE, 0, 0);

可以用 IntPtr 代替 int 数据类型

楼主是想结束外部程序,一楼答案回答的对,不过首先得获得外部程序的窗口句柄

首先在程序里定义
[DllImport("User32.dll",EntryPoint="SendMessage")]
private static extern int SendMessage( int hWnd,int Msg,int wParam,int lParam);
[DllImport("user32.dll", EntryPoint="FindWindow")]
public static extern int FindWindow (string lpClassName,string lpWindowName);

然后在你的窗体Closed事件里增加下边代码,把FindWindow函数里的参数换成你要关闭的程序标题

int iWin = FindWindow(null,"要关闭的程序的标题");
int WM_CLOSE = 0x10;
SendMessage(iWin, WM_CLOSE, 0, 0);

如果只知道程序名,不知道标题,那补充一个用进程的方法,例子是关闭记事本
Process [] localBy