欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现老板键功能的代码

程序员文章站 2022-05-15 14:29:44
c#设置热键隐藏指定窗口的代码 using system; using system.text; using system.collections; usi...

c#设置热键隐藏指定窗口的代码

using system;
using system.text;
using system.collections;
using system.runtime.interopservices;
 
namespace windowhider
{
  /// <summary>
  /// object used to control a windows form.
  /// </summary>
  public class window
  {
    /// <summary>
    /// win32 api imports
    /// </summary>
    [dllimport("user32.dll")] private static extern 
      bool showwindowasync(intptr hwnd, int ncmdshow);
    [dllimport("user32.dll")] private static extern 
      bool setforegroundwindow(intptr hwnd);
    [dllimport("user32.dll")] private static extern 
      bool isiconic(intptr hwnd);
    [dllimport("user32.dll")] private static extern 
      bool iszoomed(intptr hwnd);
    [dllimport("user32.dll")] private static extern 
      intptr getforegroundwindow();
    [dllimport("user32.dll")] private static extern 
      intptr getwindowthreadprocessid(intptr hwnd, intptr processid);
    [dllimport("user32.dll")] private static extern 
      intptr attachthreadinput(intptr idattach, intptr idattachto, int fattach);
 
    /// <summary>
    /// win32 api constants for showwindowasync()
    /// </summary>
    private const int sw_hide = 0;
    private const int sw_shownormal = 1;
    private const int sw_showminimized = 2;
    private const int sw_showmaximized = 3;
    private const int sw_shownoactivate = 4;
    private const int sw_restore = 9;
    private const int sw_showdefault = 10;
 
    /// <summary>
    /// private fields
    /// </summary>
    private intptr m_hwnd;
    private string m_title;
    private bool m_visible = true;
    private string m_process;
    private bool m_wasmax = false;
 
    /// <summary>
    /// window object's public properties
    /// </summary>
    public intptr hwnd
    {
      get{return m_hwnd;}
    }
    public string title
    {
      get{return m_title;}
    }
    public string process
    {
      get{return m_process;}
    }
 
    /// <summary>
    /// sets this window object's visibility
    /// </summary>
    public bool visible
    {
      get{return m_visible;}
      set
      {
        //show the window
        if(value == true)
        {
          if(m_wasmax)
          {
            if(showwindowasync(m_hwnd,sw_showmaximized))
              m_visible = true;
          }
          else
          {
            if(showwindowasync(m_hwnd,sw_shownormal))
              m_visible = true;
          }
        }
        //hide the window
        if(value == false)
        {
          m_wasmax = iszoomed(m_hwnd);
          if(showwindowasync(m_hwnd,sw_hide))
            m_visible = false;
        }
      }
    }
 
    /// <summary>
    /// constructs a window object
    /// </summary>
    /// <param name="title">title caption</param>
    /// <param name="hwnd">handle</param>
    /// <param name="process">owning process</param>
    public window(string title, intptr hwnd, string process)
    {
      m_title = title;
      m_hwnd = hwnd;
      m_process = process;
    }
 
    //override tostring() 
    public override string tostring()
    {
      //return the title if it has one, if not return the process name
      if (m_title.length > 0)
      {
        return m_title;
      }
      else
      {
        return m_process;
      }
    }
 
    /// <summary>
    /// sets focus to this window object
    /// </summary>
    public void activate()
    {
      if(m_hwnd == getforegroundwindow())
        return;
 
      intptr threadid1 = getwindowthreadprocessid(getforegroundwindow(),
                            intptr.zero);
      intptr threadid2 = getwindowthreadprocessid(m_hwnd,intptr.zero);
       
      if (threadid1 != threadid2)
      {
        attachthreadinput(threadid1,threadid2,1);
        setforegroundwindow(m_hwnd);
        attachthreadinput(threadid1,threadid2,0);
      }
      else
      {
        setforegroundwindow(m_hwnd);
      }
 
      if (isiconic(m_hwnd))
      {
        showwindowasync(m_hwnd,sw_restore);
      }
      else
      {
        showwindowasync(m_hwnd,sw_shownormal);
      }
    }
  }
 
  /// <summary>
  /// collection used to enumerate window objects
  /// </summary>
  public class windows : ienumerable, ienumerator
  {
    /// <summary>
    /// win32 api imports
    /// </summary>
    [dllimport("user32.dll")] private static extern 
       int getwindowtext(int hwnd, stringbuilder title, int size);
    [dllimport("user32.dll")] private static extern 
       int getwindowmodulefilename(int hwnd, stringbuilder title, int size);
    [dllimport("user32.dll")] private static extern 
       int enumwindows(enumwindowsproc ewp, int lparam); 
    [dllimport("user32.dll")] private static extern 
       bool iswindowvisible(int hwnd);
 
    //delegate used for enumwindows() callback function
    public delegate bool enumwindowsproc(int hwnd, int lparam);
 
    private int m_position = -1; // holds current index of wndarray, 
                   // necessary for ienumerable
     
    arraylist wndarray = new arraylist(); //array of windows
     
    //object's private fields
    private bool m_invisible = false;
    private bool m_notitle = false;
 
    /// <summary>
    /// collection constructor with additional options
    /// </summary>
    /// <param name="invisible">include invisible windows</param>
    /// <param name="untitled">include untitled windows</param>
    public windows(bool invisible, bool untitled)
    {
      m_invisible = invisible;
      m_notitle = untitled;
 
      //declare a callback delegate for enumwindows() api call
      enumwindowsproc ewp = new enumwindowsproc(evalwindow);
      //enumerate all windows
      enumwindows(ewp, 0);
    }
    /// <summary>
    /// collection constructor
    /// </summary>
    public windows()
    {
      //declare a callback delegate for enumwindows() api call
      enumwindowsproc ewp = new enumwindowsproc(evalwindow);
      //enumerate all windows
      enumwindows(ewp, 0);
    }
    //enumwindows callback function
    private bool evalwindow(int hwnd, int lparam)
    {
      if (m_invisible == false && !iswindowvisible(hwnd))
        return(true);
 
      stringbuilder title = new stringbuilder(256);
      stringbuilder module = new stringbuilder(256);
 
      getwindowmodulefilename(hwnd, module, 256);
      getwindowtext(hwnd, title, 256);
 
      if (m_notitle == false && title.length == 0)
        return(true);
 
      wndarray.add(new window(title.tostring(), (intptr)hwnd, 
                  module.tostring()));
 
      return(true);
    }
     
    //implement ienumerable
    public ienumerator getenumerator()
    {
      return (ienumerator)this;
    }
    //implement ienumerator
    public bool movenext()
    {
      m_position++;
      if (m_position < wndarray.count)
{
return true;
}
else
{
return false;
}
}
public void reset()
{
m_position = -1;
}
public object current
{
get
{
return wndarray[m_position];
}
}
}
}

再给大家分享一个其他网友的方法,也非常不错,详情请看注释。

using system;
using system.collections.generic;
using system.runtime.interopservices;
using system.windows.forms;
namespace drmaple
{
  class hotkey
  {
    //如果函数执行成功,返回值不为0。
    //如果函数执行失败,返回值为0。要得到扩展错误信息,调用getlasterror。
    [dllimport("user32.dll", setlasterror = true)]
    public static extern bool registerhotkey(
            intptr hwnd,        //要定义热键的窗口的句柄
      int id,           //定义热键id(不能与其它id重复)
      keymodifiers fsmodifiers,  //标识热键是否在按alt、ctrl、shift、windows等键时才会生效
      keys vk           //定义热键的内容
      );
    [dllimport("user32.dll", setlasterror = true)]
    public static extern bool unregisterhotkey(
      intptr hwnd,        //要取消热键的窗口的句柄
      int id           //要取消热键的id
      );
    //定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)
    [flags()]
    public enum keymodifiers
    {
      none = 0,
      alt = 1,
      ctrl = 2,
      shift = 4,
      windowskey = 8
    }
  }
}
//简单说明一下:
//“public static extern bool registerhotkey()”这个函数用于注册热键。由于这个函数需要引用user32.dll动态链接库后才能使用,并且
//user32.dll是非托管代码,不能用命名空间的方式直接引用,所以需要用“dllimport”进行引入后才能使用。于是在函数前面需要加上
//“[dllimport("user32.dll", setlasterror = true)]”这行语句。
//“public static extern bool unregisterhotkey()”这个函数用于注销热键,同理也需要用dllimport引用user32.dll后才能使用。
//“public enum keymodifiers{}”定义了一组枚举,将辅助键的数字代码直接表示为文字,以方便使用。这样在调用时我们不必记住每一个辅
//助键的代码而只需直接选择其名称即可。
//(2)以窗体forma为例,介绍hotkey类的使用
//在forma的activate事件中注册热键,本例中注册shift+s,ctrl+z,alt+d这三个热键。这里的id号可任意设置,但要保证不被重复。

private void form_activated(object sender, eventargs e)
{
  //注册热键shift+s,id号为100。hotkey.keymodifiers.shift也可以直接使用数字4来表示。
  hotkey.registerhotkey(handle, 100, hotkey.keymodifiers.shift, keys.s); 
  //注册热键ctrl+b,id号为101。hotkey.keymodifiers.ctrl也可以直接使用数字2来表示。
  hotkey.registerhotkey(handle, 101, hotkey.keymodifiers.ctrl, keys.b);
  //注册热键alt+d,id号为102。hotkey.keymodifiers.alt也可以直接使用数字1来表示。
  hotkey.registerhotkey(handle, 102, hotkey.keymodifiers.alt, keys.d);
}
//在forma的leave事件中注销热键。
private void frmsale_leave(object sender, eventargs e)
{
  //注销id号为100的热键设定
  hotkey.unregisterhotkey(handle, 100);
  //注销id号为101的热键设定
  hotkey.unregisterhotkey(handle, 101);
  //注销id号为102的热键设定
  hotkey.unregisterhotkey(handle, 102);
}

重载froma中的wndproc函数
/// 
/// 监视windows消息
/// 重载wndproc方法,用于实现热键响应
/// 
/// 
protected override void wndproc(ref message m)
{

  const int wm_hotkey = 0x0312;
  //按快捷键 
  switch (m.msg)
  {
    case wm_hotkey:
      switch (m.wparam.toint32())
      {
        case 100:  //按下的是shift+s
          //此处填写快捷键响应代码 
          break;
        case 101:  //按下的是ctrl+b
          //此处填写快捷键响应代码
          break;
        case 102:  //按下的是alt+d
          //此处填写快捷键响应代码
          break;
      }
    break;
  }
  base.wndproc(ref m);
}

以上所述就是本文的全部内容了,希望对大家学习c#能够有所帮助。