前言
最近应客户需求写了个winform小程序,要求此窗口显示在其他程序之上,起到一个警示作用,这个似乎并不难,只需要将form的属性ToMost设置为true即可,但是当遇到其他窗体程序也设置了此属性,就没法做到本程序一直保持前置了,然后在网上参考了一些别人的思路,最终实现了。
实现方式
如果仅想实现窗体强制前置,也并没有什么难度,只需要在程序或窗体运行的时候开启一个进程检查本程序是否前置,如果非前置则通过方法SetForegroundWindow(hWnd)将其前置即可。但是这样会出现一个问题,导致其他程序无法操作,因为此方法不仅将你的程序前置了,并且还抢了焦点。所以我通过SetWindowPos方法来实现了此功能,代码如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace ABYAntenna
{
public partial class AntennaModel : Form
{
/*
定义:[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, int hWndlnsertAfter, int X, int Y, int cx, int cy, uint Flags);
调用:API.SetWindowPos(mainhwnd, -1, 0, 0, 0, 0, 0x001 | 0x002 | 0x040);
参数:
hWndInsertAfter 窗口叠层位置
HWND_TOPMOST = -1在所用"普通层"之上的"最顶层"
HWND_TOP =0在顶层的"普通层"
HWND_BOTTOM =1在底层的"普通层"
HWND_NOTOPMOST= -2 在所有非"普通层"之上的"普通层"
uFlags 附加参数
SWP_NOSIZE =0x0001窗口大小不变(忽略CX,CY参数)
SWP_NOMOVE =0x0002不可移动窗口(忽略X,Y参数)
SWP_NOZORDER =0x0004不改变叠层顺序(忽略hWndInsertAfter参数)
SWP_NOREDRAW =0x0008不重画窗口
SWP_NOACTIVATE =0x0010不激活窗口
SWP_DRAWF