用VB6.0实现将窗体最小化到系统托盘区
C#WinForm窗口最小化到系统托盘
C#WinForm窗⼝最⼩化到系统托盘private void notifyIcon1_Click(object sender, EventArgs e){this.Visible = true;this.WindowState = FormWindowState.Normal;this.notifyIcon1.Visible = false;}主窗体中拖⼊⼀个ContextMenu控件NicontextMenu,点中控件,在上下⽂菜单中添加菜单,notifyIcon1的ContextMenu⾏为中选中NicontextMenu 作为上下⽂菜单。
复制代码代码如下:this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(ponents);this.NicontextMenu = new System.Windows.Forms.ContextMenu();this.menuItem_Hide = new System.Windows.Forms.MenuItem();this.menuItem_Show = new System.Windows.Forms.MenuItem();this.menuItem_Aubot = new System.Windows.Forms.MenuItem();this.menuItem_Exit = new System.Windows.Forms.MenuItem();this.notifyIcon1.ContextMenu = this.NicontextMenu;this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject( "NotifyIcon.Icon ")));this.notifyIcon1.Text = " ";this.notifyIcon1.Visible = true;this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);this.notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click);this.NicontextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[]{this.menuItem_Hide,this.menuItem_Show,this.menuItem_Aubot,this.menuItem_Exit});//// menuItem_Hide//this.menuItem_Hide.Index = 0;this.menuItem_Hide.Text = "隐藏 ";this.menuItem_Hide.Click += new System.EventHandler(this.menuItem_Hide_Click);//// menuItem_Show//this.menuItem_Show.Index = 1;this.menuItem_Show.Text = "显⽰ ";this.menuItem_Show.Click += new System.EventHandler(this.menuItem_Show_Click);//// menuItem_Aubot//this.menuItem_Aubot.Index = 2;this.menuItem_Aubot.Text = "关于 ";this.menuItem_Aubot.Click += new System.EventHandler(this.menuItem_Aubot_Click);//// menuItem_Exit//this.menuItem_Exit.Index = 3;this.menuItem_Exit.Text = "退出 ";this.menuItem_Exit.Click += new System.EventHandler(this.menuItem_Exit_Click);protected override void OnClosing(CancelEventArgs e){this.ShowInTaskbar = false;this.WindowState = FormWindowState.Minimized;e.Cancel = true;}protected override void OnClosing(CancelEventArgs e){//this.ShowInTaskbar = false;this.WindowState = FormWindowState.Minimized;e.Cancel = true;}private void CloseCtiServer(){timer.Enabled = false;DJ160API.DisableCard();this.NotifyIcon.Visible = false;this.Close();this.Dispose();Application.Exit();}private void HideCtiServer(){this.Hide();}private void ShowCtiServer(){this.Show();this.WindowState = FormWindowState.Normal;this.Activate();}private void CtiManiForm_Closing(object sender, ponentModel.CancelEventArgs e) {this.CloseCtiServer();}private void menuItem_Show_Click(object sender, System.EventArgs e){this.ShowCtiServer();}private void menuItem_Aubot_Click(object sender, System.EventArgs e){}private void menuItem_Exit_Click(object sender, System.EventArgs e){this.CloseCtiServer();}private void menuItem_Hide_Click(object sender, System.EventArgs e){this.HideCtiServer();}private void CtiManiForm_SizeChanged(object sender, System.EventArgs e){if(this.WindowState == FormWindowState.Minimized){this.HideCtiServer();}}private void notifyIcon1_DoubleClick(object sender,System.EventArgs e){this.ShowCtiServer();}。
应用VB6.0结合WindowsAPI编写多面板应用程序
T e eth c一> hD s d 指图像所要粘贴到的 目标 设备场景句柄 一 0 0一> 目标 设备场 景中 目标矩形 左 上角 位置进行描述 . 对 的那个点 用 目标设 备对 象的逻辑坐标表 示一 7 , 3一> l2 欲传输 图像的宽度 和高度 T e ore p tr o )h c >源 设 备 场 景 .包 r源 图 h Suc iue x d c它保存在 i t B
刖 舌
内存中 ,然后粘贴到特定的对象里 =举例说明:
点也不简单, 浯句 1
BkBI t heDes hDC 0 q t 2 SRCCO PY 00
.
我 们 都 知 道 Vsa B s i l at 做 的 很 多 事 情 u e所
维普资讯
买用第一
智 慧密集
可 花
应 用 V 6 0结合 Widw P B. no s I A
编写多面板应用程序
邱 玉 宝
摘
要
本 文主要 论 述 了怎样在 Vsa B s . i l ai 60的环 境 下 ,不利 用 D L和 第三 方控件 , u c L
像 主要 是指 图 片框 中的 图像 7 , 0 一> 源 设 备对 象 中 源 矩 形 左 上 角 位 置 进 行 描 述 的 3 20 对
程挫 _ 术的最好的体现 在 V 6的编程 环境下 .要进行这样的 B 编程技 术 ,可 有多种途径 ,其 中 ,利用外 来的 动态链接库 f L ) 已有的第 二方 A te D L和 三 ci X控 件 町以很快的 实现 然而 , v 怎样在没有 D I和 A te L ci X的情况 F 实现 这样的 功能 呢?本 v 来 文就是避 开已有的这样那样 的外来程序组 件 ,而是应用 Wi— n Iw P 中最为常用的 Bth函数的功能来实现多面顿切换 程 ls I o A i B 序 ,这样 既可 以让编 程爱好者 更加灵 活地 控制 自己的程序 , 使程 序更 为美观 ,叉能学习到 Wi o s P 程序设计技巧 ,了 n w I d A 解到 Bth函数 的用法 同时在程序的编写过程 中涉及到 T其 i B
程序最小化到托盘
VC++6.0中实现将应用程序的图标加入到Windows的系统托盘中(就是为应用程序在桌面右下角添加一个图标,和QQ类似)有位老兄说我乱贴,可能这位老兄已经看得眼花缭乱了,Shell_NotifyIcon 是一个Windows SDK的一个函数,只要你在windows下编程,不管你是BCB、VC、VB,都可以调用它来实现托盘图标,只是调用方法不同罢了。
常常能见到一些优秀的软件在运行后会将其应用程序图标加入到系统托盘中。
如果能将自己编写的应用程序的图标也加入到系统托盘中,将会使你的程序显得很有专业水准。
其实这并不困难,与系统托盘通信的函数只有一个:Shell_NotifyIcon (UINT message, NOTIFYICONDATA &m_nid);首先看一下该函数的两个参数。
第一个参数message可以取以下值:NIM_ADD 向托盘中加入一个图标; NIM_MODIFY 修改托盘中的图标;NIM_DELETE 从托盘中删除一个图标;第二个参数m_nid是NOTIFYICONDATA结构的一个引用。
该结构的原型如下:typedef struct _NOTIFYICONDATA{DWORD cbSize;// 结构的大小,必须在程序中给出HWND hWnd; //是你程序中将要接收托盘消息的窗口句柄UINT uID; // 应用程序中定义的托盘图标ID,此参数用作标识UINT uFlags; //设置属性,低三位有意义,0--7,如下://第一位//#define NIF_MESSAGE 0x1 // uCallbackMessage参数有效//第二位//#define NIF_ICON 0x2 // hIcon参数有效//第三位//#define NIF_TIP 0x4 // szTip参数有效UINT uCallbackMessage; // 自定义的消息ID值,一定不要与以有的消息ID相重。
VB最小化编程
要实现窗口最小化必须满足以下条件:1:按下最小化按钮,窗体不可见2:最小化后,最小化窗体的图标必须出现在任务栏的通知区域中3:当双击通知区域中的图标时,窗体又显示出来,同时通知区域中的图标消失.要满足上面的条件:1:首先屏蔽窗体中系统自带的最小化图标,即Form.MinButton=False 2:声明1个API函数:Public Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias " Shell_ NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICOND ATA) As Long注意:上面这个API函数在XP中没有别名,将别名去掉后为: Public Declare Function Shell_NotifyIcon Lib "shell32.dll"(ByVal dwMe ssage As Long, lpData As NOTIFYICONDATA) As Long3:声明7个常数:Public Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const NIF_ICON = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_TIP = &H4Public Const WM_MOUSEMOVE = &H200Public Const WM_LBUTTONDBLCLK = &H2034:定义1个NOTIFYICONDATA类型Public Type NOTIFYICONDATAcbSize as LonghWnd as LonguId as LonguFlags as LonguCallBackMessage as LonghIcon as LongszTip as StringEnd Type5:声明一个nid的类型Public nid as NOTIFYICONDATA思路清晰后,开始编写代码1:在窗体中画1个Command,它的Caption属性为:"最小化"2:将窗体Form的MinButton的属性设为:"False"3:在窗体中添加1个模块,模块中的代码为:Public Declare Function Shell_NotifyIcon Lib "shell32.dll"(ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As LongPublic Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const NIF_ICON = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_TIP = &H4Public Const WM_MOUSEMOVE = &H200Public Const WM_LBUTTONDBLCLK = &H203Public Type NOTIFYICONDATAcbSize as LonghWnd as LonguId as LonguFlags as LonguCallBackMessage as LonghIcon as LongszTip as StringEnd TypePublic nid as NOTIFYICONDATA4:编写Command的单击事件:Private Sub Command1_Click()nid.cbSize = Len(nid)nid.uId = vbNullnid.hWnd = Me.hWndnid.uFlags = NIF_TIP Or NIF_MESSAGE Or NIF_ICONnid.uCallBackMessage = WM_MOUSEMOVEnid.hIcon = Me.Iconnid.szTip = "窗体最小化"Shell_NotifyIcon NIM_ADD, nidMe.HideEnd Sub5:编写窗体的MouseMove事件:Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X A s Single, Y As Single)Dim msg As Longmsg = X / 15If msg = WM_LBUTTONDBLCLK ThenMe.ShowShell_NotifyIcon NIM_DELETE, nidEnd IfEnd Sub按F5启动,单击Command,看看通知区域中是不是多了个窗体的图标?双击该图标,窗体又显示出来了!一、Shell_NotifyIcon 函数说明此函数用来向任务栏托盘区域发送消息1、函数格式BOOL Shell_NotifyIcon( DWORD dwMessage,PNOTIFYIC ONDATA lpdata);2、参数说明:dwMessage为输入参数,传递发送的消息,表明要执行的操作。
最小化到托盘
If Me.WindowState = vbMinimized Then
cSysTray1.InTray = True
Me.Visible = FalseEnd If
End SLeabharlann b 点击托盘图标后让程序显示出来,如下:
Private Sub cSysTray1_MouseDown(Button As Integer, Id As Long)
Me.WindowState = vbNormal
Me.Visible = True
cSysTray1.InTray = False
Me.SetFocus
End Sub
然后在自己的VB程序中添加改控件(工程-部件-浏览)。
最好把这个ocx放到C:\WINDOWS\system32。
改控件的属性InTray属性用来设置是否显示在托盘中,True为显示在托盘,False为不显示。TrayIcon属性是在托盘中显示的图标式样。TrayTip属性是鼠标移到改控件上面显示的提示文字。如果要使程序最小化时显示到托盘,如下:
单击“最小化”按钮(标题栏的右边)将窗口缩小为任务栏上右边的图标,同时隐藏原窗体。单击或者右键托盘化的图标,可以重现原窗体。
vb中有部分api可以实现将窗体最小化的功能,但是非常繁琐。这里有一个非常简单的办法:可以用微软封装好的控件来实现,不过该控件并不在VB安装目录中,需要找到VB的安装盘(不是安装以后的目录)的COMMON\TOOLS\VB\UNSUPPRT\SYSTRAY目录,将Systray目录拷到硬盘上面并编译为ocx控件(编译前记得要先把只读属性修改掉,有时候会提示要先保存,直接保存。),
最小化到托盘
系统最小化到托盘一、托盘简介所谓的“托盘”,在Windows系统界面中,指的就是下面任务条右侧,有系统时间等等的标志的那一部分。
在程序最小化或挂起时,但有不希望占据任务栏的时候,就可以把程序放到托盘区。
二、托盘编程相关函数其实,把程序放到托盘上的本质就是先在托盘区绘制一个图标,然后把程序隐藏不见,再对托盘的图标进行消息处理,就可以了。
绘制图标以及确定图标所传送消息的函数只有一个,WINSHELLAPI BOOL WINAPI Shell_NotifyIcon(DWORD dwMessage,PNOTIFYICONDATA pnid);这个函数负责向系统传递消息,以添加、修改或删除托盘区的图标。
她的返回值是个布尔类型的。
就是说,如果返回0才成功。
参数dwMessage 是表示这个函数的应用功能是哪一方面,是添加、删除,还是修改图标。
如果是添加,则它的值为NIM_ADD;删除则是NIM_DELETE;而修改是NIM_MODIFY。
参数pnid就是具体的和程序在托盘区的图标有关系的结构了。
它的定义如下:typedef struct _NOTIFYICONDATA {DWORD cbSize;HWND hWnd;UINT uID;UINT uFlags;UINT uCallbackMessage;HICON hIcon;char szTip[64];} NOTIFYICONDATA, *PNOTIFYICONDATA;下面就对该结构各个参数进行刨析:cbSize : 结构的长度,用“位”来做单位。
一般在程序中,我们用(DWORD)sizeof(NOTIFYICONDATA) 给它赋值。
HWnd : 一个句柄,如果对托盘中的图标进行操作,相应的消息就传给这个句柄所代表的窗口。
大多数情况下是this->m_hWnd。
uID : 在工程中定义的图标IDuFlags : 这个成员标志着其他哪些成员的数据是有效的,分别为NIF_ICON, NIF_MESSAGE, NIF_TIP,分别代表着数据有效的成员是hIcon, uCallbackMessage, szTip。
用VB6.0实现将窗体最小化到系统托盘区
用VB6.0实现将窗体最小化到系统托盘区使用说明:共有两个方法,经个人实际测试(环境:xpsp3 vb6.0)第二个控件法最有效果,第一个方法在启动时确实在右下角,但是弹出后再次最小化就跑到屏幕左下角了,无法最小化,不知道是啥原因,希望大家改进代码。
本人力荐第二种小巧有效简单的方法。
方法一(作者:zheng0823)API法经测试部分有效1、新建立一个VB6工程,将Form1的ShowInTaskBar属性设置为False2、菜单:工程--添加模块按“打开”这样就添加了一个新模块,名为Module1,保存为Module1.bas3、在Module1中写下如下代码:Option ExplicitPublic Const MAX_TOOLTIP As Integer = 64Public Const NIF_ICON = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_TIP = &H4Public Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const WM_MOUSEMOVE = &H200Public Const WM_LBUTTONDOWN = &H201Public Const WM_LBUTTONUP = &H202Public Const WM_LBUTTONDBLCLK = &H203Public Const WM_RBUTTONDOWN = &H204Public Const WM_RBUTTONUP = &H205Public Const WM_RBUTTONDBLCLK = &H206Public Const SW_RESTORE = 9Public Const SW_HIDE = 0Public nfIconData As NOTIFYICONDATAPublic Type NOTIFYICONDATAcbSize As LonghWnd As LonguID As LonguFlags As LonguCallbackMessage As LonghIcon As LongszTip As String * MAX_TOOLTIPEnd TypePublic Declare Function ShowWindow Lib "user32" (ByVal hWnd As Long, ByVal nCmdShow As Long) As LongPublic Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long'4、在Form1的Load事件中写下如下代码:Private Sub Form_Load()'以下把程序放入System Tray====================================System Tray BeginWith nfIconData.hWnd = Me.hWnd.uID = Me.Icon.uFlags = NIF_ICON Or NIF_MESSAGE Or NIF_TIP.uCallbackMessage = WM_MOUSEMOVE.hIcon = Me.Icon.Handle'定义鼠标移动到托盘上时显示的Tip.szTip = App.Title + "(版本" & App.Major & "." & App.Minor & "." & App.Revision & ")" & vbNullChar.cbSize = Len(nfIconData)End WithCall Shell_NotifyIcon(NIM_ADD, nfIconData)'=============================================================System Tray EndMe.HideEnd Sub'5、在Form1的QueryUnload事件中写入如下代码:Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)Call Shell_NotifyIcon(NIM_DELETE, nfIconData)End Sub'6、在Form1的MouseMove事件中写下如下代码:Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)Dim lMsg As SinglelMsg = X / Screen.TwipsPerPixelXSelect Case lMsgCase WM_LBUTTONUP'MsgBox "请用鼠标右键点击图标!", vbInformation, "实时播音专家"'单击左键,显示窗体ShowWindow Me.hWnd, SW_RESTORE'下面两句的目的是把窗口显示在窗口最顶层'Me.Show'Me.SetFocus'' Case WM_RBUTTONUP'' PopupMenu MenuTray '如果是在系统Tray图标上点右键,则弹出菜单MenuTray'' Case WM_MOUSEMOVE'' Case WM_LBUTTONDOWN'' Case WM_LBUTTONDBLCLK'' Case WM_RBUTTONDOWN'' Case WM_RBUTTONDBLCLK'' Case ElseEnd SelectEnd Sub7、现在将程序保存起来运行看看系统托盘处是否增加了一个本工程的图标。
怎么能让VB 程序最小化时在托盘显示呀急急急!~希望VB高手帮忙!
给你个例子吧建立一个frmmain主窗体Option ExplicitPrivate Sub Form_Load()'初始化imgIcon控件的Picture属性imgIcon.Picture = LoadPicture(App.Path & "\" & "heart.ico") mnuTrayShow.Enabled = False'初始化NOTIFYICONDATA数据结构Dim nid As NOTIFYICONDATAnid.cbSize = Len(nid)nid.hwnd = frmTemp.hwndnid.uId = 1&nid.uFlags = NIF_ICON Or NIF_TIP Or NIF_MESSAGE nid.uCallbackMessage = WM_NOTIFYICONnid.hicon = imgIcon.Picturenid.szTip = "系统托盘中的图标" & Chr(0)'调用Shell_NotifyIcon函数将图标加入到系统托盘中Shell_NotifyIcon NIM_ADD, nidEnd SubPrivate Sub Form_Unload(Cancel As Integer)'设置自定义类型的变量的内容Dim nid As NOTIFYICONDATAnid.cbSize = Len(nid)nid.hwnd = frmTemp.hwndnid.uId = 1&nid.uFlags = 0'调用Shell_NotifyIcon方法来删除系统托盘中的图标Shell_NotifyIcon NIM_DELETE, nidUnload frmTempEnd SubPrivate Sub mnuTrayExit_Click()Unload MeEnd SubPrivate Sub mnuTrayHide_Click()'隐藏窗体,并相应改变菜单项的状态Me.HidemnuTrayHide.Enabled = FalsemnuTrayShow.Enabled = TrueEnd SubPrivate Sub mnuTrayIcon_Click()'设置dlgOpen公用对话框的属性,以便取得相应的图标文件dlgOpen.Filter = "图标文件(*.ico)|*.ico"dlgOpen.Flags = cdlOFNFileMustExistdlgOpen.ShowOpenIf dlgOpen.FileName = "" Then Exit Sub'根据所取得图标文件,来改变imgIcon文件的属性imgIcon.Picture = LoadPicture(dlgOpen.FileName)'设置NOTIFYICONDATA数据结构Dim nid As NOTIFYICONDATAnid.cbSize = Len(nid)nid.hwnd = frmTemp.hwndnid.uId = 1&nid.uFlags = NIF_ICONnid.hicon = imgIcon.Picture'调用Shell_NotifyIcon函数来修改系统托盘中的图标Shell_NotifyIcon NIM_MODIFY, nidEnd SubPrivate Sub mnuTrayShow_Click()'显示窗体,并相应改变菜单项的状态Me.ShowmnuTrayHide.Enabled = TruemnuTrayShow.Enabled = FalseEnd SubPrivate Sub mnuTrayTip_Click()Dim str As Stringstr = InputBox("输入系统托盘中的图标的提示信息:", "提示信息") If str = "" Then Exit Sub'设置NOTIFYICONDATA数据结构Dim nid As NOTIFYICONDATAnid.cbSize = Len(nid)nid.hwnd = frmTemp.hwndnid.uId = 1&nid.uFlags = NIF_TIPnid.szTip = str & Chr(0)'调用Shell_NotifyIcon函数来修改系统托盘中的图标的提示Shell_NotifyIcon NIM_MODIFY, nidEnd Sub再建立一个空窗体叫frmTemp再建一个模块,名字随便了Option Explicit'声明Shell_NotifyIcon函数,用于将图标加入到系统托盘中Public Declare Function Shell_NotifyIcon Lib "shell32" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, pnid As NOTIFYICONDATA) As Boolean'声明自定义的数据类型NOTIFYICONDATAPublic Type NOTIFYICONDATAcbSize As Longhwnd As LonguId As LonguFlags As LonguCallbackMessage As Longhicon As LongszTip As String * 64End Type'声明常量Public Const NIM_ADD = &H0Public Const NIM_MODIFY = &H1Public Const NIM_DELETE = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_ICON = &H2Public Const NIF_TIP = &H4'定义SetWindowLong,用以改变frmTemp窗体的窗体函数Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long'定义事件的常数代码Public Const WM_LBUTTONDOWN = &H201Public Const WM_RBUTTONDOWN = &H204Public Const WM_USER = &H400'定义自定义的事件WM_NOTIFYICONPublic Const WM_NOTIFYICON = WM_USER + &H100'替换窗口处理函数Public Const GWL_WNDPROC = (-4)'该函数为frmTest的窗体处理函数。
VB窗体如何缩小到系统任务栏
如何使用直接从 Visual Basic 系统任务栏本文演示了如何充分利用 Windows 系统送纸器或使用 Visual Basic 的任务栏通知区域。
它将您选择的图标放入任务栏通知区域时鼠标 rested 通过它,将还原应用程序时单击了,并将显示一个弹出式菜单将显示您选择的工具提示的时用鼠标右键单击。
这是所有可能引起的直接处理回调的 Visual Basic 的能力,因此利用完全Shell_NotifyIcon 函数的 Shell32.dll 由被导出。
可以向任何可视的基本项目具有至少一个窗体和标准模块添加下面的示例。
分步示例将下面的代码添加到项目中的标准模块的声明部分:1. 'user defined type required by Shell_NotifyIcon API call2. Public Type NOTIFYICONDATA3. cbSize As Long4. hwnd As Long5. uId As Long6. uFlags As Long7. uCallBackMessage As Long8. hIcon As Long9. szTip As String * 6410. End Type11.12. 'constants required by Shell_NotifyIcon API call:13. Public Const NIM_ADD = &H014. Public Const NIM_MODIFY = &H115. Public Const NIM_DELETE = &H216. Public Const NIF_MESSAGE = &H117. Public Const NIF_ICON = &H218. Public Const NIF_TIP = &H419. Public Const WM_MOUSEMOVE = &H20020. Public Const WM_LBUTTONDOWN = &H201 'Button down21. Public Const WM_LBUTTONUP = &H202 'Button up22. Public Const WM_LBUTTONDBLCLK = &H203 'Double-click23. Public Const WM_RBUTTONDOWN = &H204 'Button down24. Public Const WM_RBUTTONUP = &H205 'Button up25. Public Const WM_RBUTTONDBLCLK = &H206 'Double-click26.27. Public Declare Function SetForegroundWindow Lib "user32"_28. (ByVal hwnd As Long) As Long29. Public Declare Function Shell_NotifyIcon Lib "shell32" _30. Alias "Shell_NotifyIconA" _31. (ByVal dwMessage As Long, pnid As NOTIFYICONDATA) AsBoolean32.33. Public nid As NOTIFYICONDATA34.下面的代码添加到您要为您的应用程序响应系统任务栏图标或通知图标在项目中的任何窗体:35. Private Sub Form_Load()36. 'the form must be fully visible before callingShell_NotifyIcon37. Me.Show38. Me.Refresh39. With nid40. .cbSize = Len(nid)41. .hwnd = Me.hwnd42. .uId = vbNull43. .uFlags = NIF_ICON Or NIF_TIP Or NIF_MESSAGE44. .uCallBackMessage = WM_MOUSEMOVE45. .hIcon = Me.Icon46. .szTip = "Your ToolTip" & vbNullChar47. End With48. Shell_NotifyIcon NIM_ADD, nid49. End Sub50.51. Private Sub Form_MouseMove(Button As Integer, Shift AsInteger, X As Single, Y As Single)52. 'this procedure receives the callbacks from the SystemTray icon.53. Dim Result As Long54. Dim msg As Long55. 'the value of X will vary depending upon the scalemodesetting56. If Me.ScaleMode = vbPixels Then57. msg = X58. Else59. msg = X / Screen.TwipsPerPixelX60. End If61. Select Case msg62. Case WM_LBUTTONUP '514 restore form window63. Me.WindowState = vbNormal64. Result = SetForegroundWindow(Me.hwnd)65. Me.Show66. Case WM_LBUTTONDBLCLK '515 restore form window67. Me.WindowState = vbNormal68. Result = SetForegroundWindow(Me.hwnd)69. Me.Show70. Case WM_RBUTTONUP '517 display popup menu71. Result = SetForegroundWindow(Me.hwnd)72. Me.PopupMenu Me.mPopupSys73. End Select74. End Sub75.76. Private Sub Form_Resize()77. 'this is necessary to assure that the minimized windowis hidden78. If Me.WindowState = vbMinimized Then Me.Hide79. End Sub80.81. Private Sub Form_Unload(Cancel As Integer)82. 'this removes the icon from the system tray83. Shell_NotifyIcon NIM_DELETE, nid84. End Sub85.86. Private Sub mPopExit_Click()87. 'called when user clicks the popup menu Exit command88. Unload Me89. End Sub90.91. Private Sub mPopRestore_Click()92. 'called when the user clicks the popup menu Restorecommand93. Dim Result As Long94. Me.WindowState = vbNormal95. Result = SetForegroundWindow(Me.hwnd)96. Me.Show97. End Sub98.使上面的代码添加到同一窗体上的以下属性设置:99. Property Required Setting for Taskbar NotificationArea example100. -----------------------------------------------------------------------101. Icon = The icon you want to appear in the system tray.102. Minbutton = True103. ShownInTaskbar = False104.将下面的菜单项添加到同一窗体使用菜单编辑器:105. Caption Name Enabled Visible Position 106. --------------------------------------------------------- 107. &SysTray mPopupSys True False Main Level 108. &Restore mPopRestore True True Inset one 109. &Exit mPopExit True True Inset one您可以根据需要添加更多菜单项。
利用VB实现系统托盘技术
利用VB实现系统托盘技术作者:赵汝苓来源:《中国新通信》2017年第05期【摘要】通过调用API函数实现系统托盘技术,主要涉及到API的几个常用函数的声明和调用,再结合VB本身的特征综合运用。
【关键词】 API 系统托盘消息机制系统托盘常指Windows任务栏的状态区域,系统时钟、音量控制等程序都在系统托盘中,一些应用程序在安装完后也将它们本身的图标放入了其中。
一般来说,系统托盘驻留程序是在计算机后台运行,如瑞星、MSN等。
系统托盘主要以特殊的小图标在任务栏右边时间的区域出现,作为程序运行的一个标志,我们可以通过使用小图标所弹出的菜单来控制应用程序状态,可实现修改该图标、窗口复位、最大化、最小化及关闭程序等功能。
利用VB调用API可以实现功能比较完整的托盘程序,牵涉到Shell_NotifyIcon、SendMassage、CallWindowProc、SetWindowLong等API函数,其中Shell_NotifyIcon是主要的函数,它用来添加、删除、更改系统托盘区的图标,SendMassage、CallWindowProc、SetWindowLong函数,通过WINDOWS操作系统的消息机制,实现对应用程序的控制。
一、先介绍相关的API函数、关键字1、Shell_NotifyIcon用于添加、删除、更改系统托盘区的图标;2、SendMassage用于将一条消息发给某个窗口;3、CallWindowProc用于发送消息到一个窗口过程;4、SetWindowLong 用于使窗口结构中为指定的窗口设置属性,SetWindowLong函数作用是取得默认窗口过程的地址,然后转向自定义的窗口过程的地址。
5、消息机制。
Windows消息控制中心一般是三层结构,其顶端就是Windows内核。
Windows内核维护着一个消息队列,第二季控制中心从这个消息队列中获取自己管辖的消息,后作出处理,有些消息直接处理掉,有些还要发送给下一级窗体或控件。
VB6.0代码实现将指定窗体移入另一指定窗体中
Handle = FindWindow(vbNullString, "要被移入的窗体标题名称") '可手工输入,也可通过程序获取后调用
nStyle = WS_Visible Or WS_Caption Or WS_CLIPSIBLINGS '窗体风格样式
Ret = SetWindowLong(Handle, GWL_STYLE, nStyle)
本段VB6.0代码可以实现将指定窗体移入另一指定窗体中
Option Explicit
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
'指定一个窗口的新父(在vb里使用:利用这个函数,vb可以多种形式支持子窗口。例如,可将控件从一个容器移至窗体中的另一个。用这个函数在窗体间移动控件是相当冒险的,
'但却不失为一个有效的办法。如真的这样做,请在关闭任何一个窗体之前,注意用SetParent将控件的父设回原来的那个)
'返回值Long,前一个父窗口的句柄
'hWndChild Long,子窗口的句柄
'hWndNewParent Long,hWndChild的新父
'可用这个函数在运行期将vb控件置入容器控件内部(比如将一个按钮设成图象或窗体控件的子窗口),或者将控件从一个容器控件移至另一个。控件移至另一个父后,它的位置
'将由新父的坐标系统决定。这样一来,有必要重新规定控件的位置,使其能在目标位置显示出来
WinForm实现最小化到系统托盘方法实例详解
WinForm实现最⼩化到系统托盘⽅法实例详解本⽂实例讲述了WinForm实现最⼩化到系统托盘⽅法。
分享给⼤家供⼤家参考。
具体分析如下:有个叫NotifyIcon的控件1、建个WinForm项⽬,其它操作略过。
2、拉个NotifyIcon控件,将属性Visable设置成False,在Text属性上随便填些⽂件。
3、实现Form的SizeChanged事件,代码如下:if(this.WindowState == FormWindowState.Minimized) //判断是否最⼩化{this.ShowInTaskbar = false; //不显⽰在系统任务栏notifyIcon.Visible = true; //托盘图标可见}4、实现NotifyIcon控件的DoubleClick事件,代码如下:if(this.WindowState == FormWindowState.Minimized){this.ShowInTaskbar = true; //显⽰在系统任务栏this.WindowState = FormWindowState.Normal; //还原窗体notifyIcon.Visible = false; //托盘图标隐藏}例题:private ContextMenu notifyiconMnu;#region 最⼩化到任务栏/// <summary>/// 最⼩化到任务栏/// </summary>private void Initializenotifyicon(){//定义⼀个MenuItem数组,并把此数组同时赋值给ContextMenu对象MenuItem[] mnuItms = new MenuItem[3];mnuItms[0] = new MenuItem();mnuItms[0].Text = "显⽰窗⼝";mnuItms[0].Click += new System.EventHandler(this.notifyIcon1_showfrom);mnuItms[1] = new MenuItem("-");mnuItms[2] = new MenuItem();mnuItms[2].Text = "退出系统";mnuItms[2].Click += new System.EventHandler(this.ExitSelect);mnuItms[2].DefaultItem = true;notifyiconMnu = new ContextMenu(mnuItms);notifyIcon1.ContextMenu = notifyiconMnu;//为托盘程序加⼊设定好的ContextMenu对象}private void notifyIcon1_DoubleClick(object sender, EventArgs e){if (this.WindowState == FormWindowState.Minimized){this.Show();this.ShowInTaskbar = true;this.WindowState = FormWindowState.Normal;notifyIcon1.Visible = false;}}public void notifyIcon1_showfrom(object sender, System.EventArgs e){if (this.WindowState == FormWindowState.Minimized){this.Show();this.ShowInTaskbar = true;this.WindowState = FormWindowState.Normal;notifyIcon1.Visible = false;}}public void ExitSelect(object sender, System.EventArgs e){//隐藏托盘程序中的图标notifyIcon1.Visible = false;//关闭系统this.Close();this.Dispose(true);}#endregionprivate void Form_main_SizeChanged(object sender, EventArgs e) {if (this.WindowState == FormWindowState.Minimized)//判断是否最⼩化{notifyIcon1.Visible = true;this.Hide();this.ShowInTaskbar = false;Initializenotifyicon();}}希望本⽂所述对⼤家的C#程序设计有所帮助。
VB实现在窗口的标题栏上添加一个按钮的功能实现程序最小化到系统托盘
程序运行窗口在窗口的标题栏上添加了一个按钮,实现最小化到系统托盘右键菜单1、复制以下程序段到记事本中另存为文件:Type=ExeReference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\WINDOWS\system32\std ole2.tlb#OLE AutomationModule=TrayStartup="frmMain"HelpFile=""ExeName32="Project1.exe"Path32="..\..\..\..\..\..\WINDOWS\Desktop"Command32=""Name="Project1"HelpContextID="0"CompatibleMode="0"MajorVer=1MinorVer=0RevisionVer=0AutoIncrementVer=0ServerSupportFiles=0VersionCompanyName="None"CompilationType=0OptimizationType=0FavorPentiumPro(tm)=0CodeViewDebugInfo=0NoAliasing=0BoundsCheck=0OverflowCheck=0 FlPointCheck=0 FDIVCheck=0 UnroundedFP=0 StartMode=0 Unattended=0 Retained=0 ThreadPerObject=0 MaxNumberOfThreads=1[MS Transaction Server] AutoRefresh=1Begin VB.Form frmMainAutoRedraw = -1 'TrueCaption = "TitleBar Tray Button Demo"ClientHeight = 2040ClientLeft = 60ClientTop = 345ClientWidth = 4680LinkTopic = "Form1"ScaleHeight = 2040ScaleWidth = 4680StartUpPosition = 3 '窗口缺省Begin VB.Menu mnuPopUpCaption = ""Visible = 0 'FalseBegin VB.Menu mnuRestoreCaption = "Restore"EndEndEndAttribute VB_Name = "frmMain"Attribute VB_GlobalNameSpace = FalseAttribute VB_Creatable = FalseAttribute VB_PredeclaredId = TrueAttribute VB_Exposed = FalsePrivate Sub Form_Load()Print "Right Click For Menu"Me.ScaleMode = vbPixels 'The API works in pixelsHook Me 'FormHook Hook()End SubPrivate Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)If Button = 2 Then TrayMenu Me 'TrayNotify TrayMneu()End SubPrivate Sub Form_Unload(Cancel As Integer)UnHook 'FormHook UnHook()End SubAttribute VB_Name = "ToolTip"Const WS_EX_TOPMOST = &H8&Const TTS_ALWAYSTIP = &H1Const HWND_TOPMOST = -1Const SWP_NOACTIVATE = &H10Const SWP_NOMOVE = &H2Const SWP_NOSIZE = &H1Const WM_USER = &H400Const TTM_ADDTOOLA = (WM_USER + 4)Const TTF_SUBCLASS = &H10Declare Function CreateWindowEx Lib "user32" Alias "CreateWindowExA" (ByVal dwExStyle As Long, ByVal lpClassName As String, ByVal lpWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hWndParent As Long, ByVal hMenu As Long, ByVal hInstance As Long, lpParam As Any) As Long Declare Function DestroyWindow Lib "user32" (ByVal hwnd As Long) As Long Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As LongPublic Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As LongType TOOLINFOcbSize As LonguFlags As Longhwnd As Longuid As LongRECT As RECThinst As LonglpszText As StringlParam As LongEnd TypePublic hWndTT As LongPublic Sub CreateTip(hwndForm As Long, szText As String, rct As RECT)hWndTT = CreateWindowEx(WS_EX_TOPMOST, "tooltips_class32", "",TTS_ALWAYSTIP, _0, 0, 0, 0, hwndForm, 0&, App.hInstance, 0&)SetWindowPos hWndTT, HWND_TOPMOST, 0, 0, 0, 0, _SWP_NOMOVE Or SWP_NOSIZE Or SWP_NOACTIVATEDim TI As TOOLINFOWith TI.cbSize = Len(TI).uFlags = TTF_SUBCLASS.hwnd = hwndForm.uid = 1&.lpszText = szText & vbNullChar.RECT = rctEnd WithSendMessage hWndTT, TTM_ADDTOOLA, 0, TIEnd SubPublic Sub KillTip()DestroyWindow hWndTTEnd Sub4、复制以下程序段到记事本中另存为文件:Attribute VB_Name = "DrawButton"Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long Declare Function DrawFrameControl Lib "user32" (ByVal hdc As Long, lpRect As RECT, ByVal un1 As Long, ByVal un2 As Long) As LongDeclare Function GetTitleBarInfo Lib "user32" (ByVal hwnd As Long, pti As TitleBarInfo) As BooleanDeclare Function FillRect Lib "user32" (ByVal hdc As Long, lpRect As RECT, ByVal hBrush As Long) As LongDeclare Function GetSysColorBrush Lib "user32" (ByVal nIndex As Long) As LongDeclare Function OffsetRect Lib "user32" (lpRect As RECT, ByVal x As Long, ByVal y As Long) As LongType RECTLeft As LongTop As LongRight As LongBottom As LongEnd TypeType TitleBarInfocbSize As LongrcTitleBar As RECT 'A RECT structure that receives the coordinates of the title barrgState(5) As Long 'An array that receives a DWORD value for each element of the title barEnd Type'rgState array Values'0 The titlebar Itself'1 Reserved'2 Min button'3 Max button'4 Help button'5 Close button''rgstate return constatnts'STATE_SYSTEM_FOCUSABLE = &H00100000'STATE_SYSTEM_INVISIBLE = &H00008000'STATE_SYSTEM_OFFSCREEN = &H00010000'STATE_SYSTEM_PRESSED = &H00000008'STATE_SYSTEM_UNAVAILABLE = &H00000001Const DFC_BUTTON = 4Const DFCS_BUTTONPUSH = &H10Const DFCS_PUSHED = &H200Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As Long) As LongPublic Declare Function PtInRect Lib "user32" (lpRect As RECT, ByVal x As Long, ByVal y As Long) As LongPublic Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As LongPublic Type POINTAPIx As Longy As LongEnd TypeConst SM_CXFRAME = 32Const COLOR_BTNTEXT = 18Dim lDC As LongPublic R As RECTPublic Sub ButtonDraw(frm As Form, bState As Boolean)Dim TBButtons As IntegerDim TBarHeight As IntegerDim TBButtonHeight As IntegerDim TBButtonWidth As IntegerDim DrawWidth As IntegerDim TBI As TitleBarInfoDim TBIRect As RECTDim bRslt As BooleanDim WinBorder As IntegerWith frmIf .BorderStyle = 0 Then Exit Sub ' Don't draw a button if there is no titlebar'----How Many Buttons in TitleBar------------------------------------------If Not .ControlBox Then TBButtons = 0If .ControlBox Then TBButtons = 1If .ControlBox And .WhatsThisButton ThenIf .BorderStyle < 4 ThenTBButtons = 2ElsetButtons = 1End IfEnd IfIf .ControlBox And .MinButton And .BorderStyle = 2 Then TBButtons = 3If .ControlBox And .MinButton And .BorderStyle = 5 Then TBButtons = 1If .ControlBox And .MaxButton And .BorderStyle = 2 Then TBButtons = 3If .ControlBox And .MaxButton And .BorderStyle = 5 Then TBButtons = 1'------------------------------------------------------------------------'----Get height of Titlebar----------------------------------------------'Using this method gets the height of the titlebar regardless of the window'style. It does, however, restrict its use to Win98/2000. So if you want to'use this code in Win95, then call GetSystemMetrics to find the windowstyle'and titlebar size.TBI.cbSize = Len(TBI)bRslt = GetTitleBarInfo(.hwnd, TBI)TBarHeight = TBIRect.Bottom - TBIRect.Top - 1'-----------------------------------------------------------------------'----Get WindowBorder Size----------------------------------------------If .BorderStyle = 2 Or .BorderStyle = 5 ThenR.Top = GetSystemMetrics(32) + 2WinBorder = R.Top - 6ElseR.Top = 5WinBorder = -1End IfEnd With'---------------------------------------------------------------------------'----Use Titlebar Height to determin button size----------------------------TBButtonHeight = TBarHeight - 4TBButtonWidth = TBButtonHeight + 2'and the size and space of the dot on the buttonDrawWidth = TBarHeight / 8'---------------------------------------------------------------------------'----Determin the position of our button------------------------------------R.Bottom = R.Top + TBButtonHeightSelect Case TBButtonsCase 1R.Right = frm.ScaleWidth - (TBButtonWidth) + WinBorderCase 2R.Right = frm.ScaleWidth - ((TBButtonWidth * 2) + 2) + WinBorderCase 3R.Right = frm.ScaleWidth - ((TBButtonWidth * 3) + 2) + WinBorderCase ElseEnd SelectR.Left = R.Right - TBButtonWidth'--------------------------------------------------------------------------'----Get the Widow DC so that we may draw in the title bar-----------------lDC = GetWindowDC(frm.hwnd)'--------------------------------------------------------------------------'----Determin the position of thedot--------------------------------------Dim StartXY As Integer, EndXY As IntegerSelect Case TBarHeightCase Is < 20StartXY = DrawWidth + 1EndXY = DrawWidth - 1Case ElseStartXY = (DrawWidth * 2)EndXY = DrawWidthEnd Select'--------------------------------------------------------------------------'----We have all the information we need So Draw the button----------------Dim rDot As RECTIf bState ThenDrawFrameControl lDC, R, DFC_BUTTON, DFCS_BUTTONPUSH Or DFCS_PUSHEDrDot.Left = R.Right - (1 + StartXY): rDot.Top = R.Bottom - (1 + StartXY)rDot.Right = R.Right - (1 + EndXY): rDot.Bottom = R.Bottom - (1 + EndXY)ElseDrawFrameControl lDC, R, DFC_BUTTON, DFCS_BUTTONPUSHrDot.Left = R.Right - (2 + StartXY): rDot.Top = R.Bottom - (2 + StartXY)rDot.Right = R.Right - (2 + EndXY): rDot.Bottom = R.Bottom - (2 + EndXY)End IfFillRect lDC, rDot, GetSysColorBrush(COLOR_BTNTEXT)'---------------------------------------------------------------------------'----SetTooltip------------------------------------------------------------ Dim TTRect As RECTTTRect.Bottom = R.Bottom + (TBarHeight - ((TBarHeight * 2) + WinBorder + 5))TTRect.Left = R.Left - (4 - WinBorder)TTRect.Right = R.Right - (4 - WinBorder)TTRect.Top = R.Top + (TBarHeight - ((TBarHeight * 2) + WinBorder + 5))KillTip 'ToolTip KillTip()CreateTip appForm.hwnd, "System Tray", TTRect 'ToolTip CreateTip()End Sub5、复制以下程序段到记事本中另存为文件:Attribute VB_Name = "TrayNotify"Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As LongDeclare Function CreatePopupMenu Lib "user32" () As LongDeclare Function TrackPopupMenu Lib "user32" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal x As Long, ByVal y As Long, ByVal nReserved As Long, ByVal hwnd As Long, ByVal lprc As Any) As LongDeclare Function AppendMenu Lib "user32" Alias "AppendMenuA" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal wIDNewItem As Long, ByVal lpNewItem As Any) As LongDeclare Function DestroyMenu Lib "user32" (ByVal hMenu As Long) As LongType NOTIFYICONDATAcbSize As Longhwnd As Longuid As LonguFlags As LonguCallbackMessage As LonghIcon As Longsztip As String * 64End TypeConst NIM_ADD = &H0Const NIM_DELETE = &H2Const NIM_MODIFY = &H1Const NIF_MESSAGE = &H1Const NIF_ICON = &H2Const NIF_TIP = &H4Const MF_GRAYED = &H1&Const MF_STRING = &H0&Const MF_SEPARATOR = &H800&Const TPM_NONOTIFY = &H80&Const TPM_RETURNCMD = &H100&Public bTraySet As BooleanDim lMenu As LongPublic Sub TraySet(frm As Form, sztip As String, hIcon As Long)Dim NID As NOTIFYICONDATAWith NID.cbSize = Len(NID).hIcon = hIcon.sztip = sztip & vbNullChar.uCallbackMessage = WM_LBUTTONUP.uFlags = NIF_MESSAGE Or NIF_ICON Or NIF_TIP .uid = 1&End WithShell_NotifyIcon NIM_ADD, NIDbTraySet = TrueEnd SubPublic Sub TrayRestore(frm As Form)Dim NID As NOTIFYICONDATAWith NID.cbSize = Len(NID).uid = 1&End WithShell_NotifyIcon NIM_DELETE, NIDbTraySet = FalseEnd SubPublic Sub TrayMenu(frm As Form)Dim hMenu As Long, tMenu As LongDim MP As POINTAPIGetCursorPos MPhMenu = CreatePopupMenu()If bTraySet ThenAppendMenu hMenu, MF_STRING, 1000, "Restore" ElseAppendMenu hMenu, MF_STRING Or MF_GRAYED, 1000, "Restore"End IfAppendMenu hMenu, MF_SEPARATOR, 0&, 0&AppendMenu hMenu, MF_STRING, 1010, "Exit"tMenu = TrackPopupMenu(hMenu, TPM_NONOTIFY Or TPM_RETURNCMD, MP.x, MP.y, 0&, frm.hwnd, 0&)Select Case tMenuCase 1000TrayRestore frmCase 1010TrayRestore frmUnHookUnload frmCase Else'do nothingEnd SelectDestroyMenu hMenuEnd Sub6、复制以下程序段到记事本中另存为文件:Attribute VB_Name = "FormHook"Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" _ (ByVal lpPrevWndFunc As Long, _ByVal hwnd As Long, _ByVal Msg As Long, _ByVal wParam As Long, _ByVal lParam As Long) As LongDeclare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" _ (ByVal hwnd As Long, _ByVal nIndex As Long, _ByVal dwNewLong As Long) As LongDeclare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As IntegerPublic Const GWL_WNDPROC = -4Public Const WM_LBUTTONDOWN = &H201Public Const WM_LBUTTONUP = &H202Public Const WM_MOUSEMOVE = &H200Public Const WM_NCMOUSEMOVE = &HA0Public Const WM_NCLBUTTONDOWN = &HA1Public Const WM_NCLBUTTONUP = &HA2Public Const WM_NCLBUTTONDBLCLK = &HA3Public Const WM_NCRBUTTONDOWN = &HA4Public Const WM_NCRBUTTONUP = &HA5Public Const WM_ACTIVATE = &H6Public Const WM_NCPAINT = &H85Public Const WM_PAINT = &HFPublic Const WM_ACTIVATEAPP = &H1CPublic Const WM_MOUSEACTIVATE = &H21Public Const WM_COMMAND = &H111Public Const WM_NCACTIVATE = &H86Public Const WM_DESTROY = &H2Public Const WM_SIZE = &H5Global lpPrevWndProc As LongGlobal gHW As LongGlobal appForm As FormPrivate Function MakePoints(lParam As Long) As POINTAPIDim hexstr As Stringhexstr = Right("00000000" & Hex(lParam), 8)MakePoints.x = CLng("&H" & Right(hexstr, 4)) - (appForm.Left / Screen.TwipsPerPixelX)MakePoints.y = CLng("&H" & Left(hexstr, 4)) - (appForm.Top / Screen.TwipsPerPixelY)End FunctionPublic Sub Hook(frm As Form)Set appForm = frmlpPrevWndProc = SetWindowLong(gHW, GWL_WNDPROC, AddressOf WindowProc)End SubPublic Sub UnHook()Dim lngReturnValue As LonglngReturnValue = SetWindowLong(gHW, GWL_WNDPROC, lpPrevWndProc) End SubFunction WindowProc(ByVal hwnd As Long, _ByVal uMsg As Long, _ByVal wParam As Long, _ByVal lParam As Long) As Long'------------------------------------------------------------------------------'Messing around in here can cause allsorts of problems.'So, if you must, make sure you save everytihing you want to keep 'before you run the program.'Don't run anything outside of a message selection as it will be 'executed so many times per second that it will slow down system response.Dim lRslt As LongDim retProc As BooleanStatic STButtonState As BooleanStatic Toggle As BooleanStatic i As IntegerOn Error Resume NextSelect Case uMsgCase WM_DESTROYTrayRestore appFormKillTip 'ToolTip KillTip()UnHookretProc = TrueCase WM_NCMOUSEMOVE'Only draw the button when necessaryIf GetAsyncKeyState(vbLeftButton) < 0 ThenIf OverButton(lParam) ThenIf Toggle = False ThenToggle = TrueButtonDraw appForm, Toggle 'DrawButton ButtonDraw()End IfElseIf Toggle = True ThenToggle = FalseButtonDraw appForm, Toggle 'DrawButton ButtonDraw()End IfEnd IfElseSTButtonState = FalseretProc = TrueEnd IfCase WM_NCLBUTTONDOWNIf OverButton(lParam) ThenSTButtonState = TrueButtonDraw appForm, True 'DrawButton ButtonDraw()ElseSTButtonState = FalseretProc = TrueEnd IfCase WM_NCLBUTTONUPSTButtonState = FalseIf OverButton(lParam) ThenTraySet appForm, appForm.Caption, appForm.Icon'TrayNotify TraySet()ButtonDraw appForm, False 'DrawButton ButtonDraw()retProc = FalseElseretProc = TrueEnd IfCase WM_LBUTTONUPSTButtonState = FalseButtonDraw appForm, False 'DrawButton ButtonDraw()If GetAsyncKeyState(vbLeftButton) < 0 And bTraySet Then TrayMenu appForm 'TrayNotify TrayMenu()End IfretProc = TrueCase WM_NCLBUTTONDBLCLK, WM_NCRBUTTONDOWNIf Not OverButton(lParam) ThenretProc = TrueEnd IfCase WM_SIZE, WM_NCPAINT, WM_PAINT, WM_COMMANDButtonDraw appForm, False 'DrawButton ButtonDraw()retProc = TrueCase WM_ACTIVATEAPP, WM_NCACTIVATE, WM_ACTIVATE, WM_MOUSEACTIVATEButtonDraw appForm, False 'DrawButton ButtonDraw()retProc = TrueCase ElseretProc = TrueEnd SelectIf retProc ThenWindowProc = CallWindowProc(lpPrevWndProc, hwnd, uMsg, wParam, lParam)ElseWindowProc = 0End IfEnd FunctionPrivate Function OverButton(lParam As Long) As Boolean Dim MP As POINTAPIMP = MakePoints(lParam)If PtInRect(R, MP.x, MP.y) Then OverButton = True End Function双击工程文件:运行,就可以看到效果。
如何使程序最小化到系统托盘
如何使程序最小化到系统托盘VC编写的应用程序希望像qq,千千静听,暴风影音那样程序最小化时在系统托盘中显示而不是在任务栏中。
如下:1.在基于对话框的程序的头文件中添加成员变量NOTIFYICODATA m_nid2.自定义消息函数OnShowTask1)首先在头文件中定义 #define WM_SHOWTASK WM_USER+12)在头文件映射中在添加afx_msg LRESULT OnShowTask(WPARAM wParam,LPARAM lParam)3)在源文件中的消息映射队列中添加ON_MESSAGE (WM_SHOWTASK,OnShowTask)4)在原文件中添加自定义消息函数定义:LRESULT CMediaPlayerDialog::OnShowTask(WPARAM wParam,LPARAM lParam){if(wParam != IDR_MAINFRAME)return 1;switch(lParam){case WM_RBUTTONUP: // 右键起来时弹出菜单{LPPOINT lpoint = new tagPOINT;::GetCursorPos(lpoint); // 得到鼠标位置CMenu menu;menu.CreatePopupMenu(); // 声明一个弹出式菜单menu.AppendMenu(MF_STRING, WM_DESTROY, "退出(&X)");menu.TrackPopupMenu(TPM_LEFTALIGN,lpoint->x ,lpoint->y, this);HMENU hmenu = menu.Detach();menu.DestroyMenu();delete lpoint;}break;case WM_LBUTTONDBLCLK: // 双击左键的处理{this->ShowWindow(SW_SHOWNORMAL); // 显示主窗口}break;}return 0;}3.在程序的InitDialog函数中添加如下代码://---------------------------托盘显示初始化---------------------------------//m_nid.cbSize = (DWORD)sizeof(NOTIFYICONDATA);m_nid.hWnd = this->m_hWnd;m_nid.uID = IDR_MAINFRAME;m_nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP ;m_nid.uCallbackMessage = WM_SHOWTASK; // 自定义的消息名称m_nid.hIcon = LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAI NFRAME));strcpy(m_nid.szTip, "自制播放器"); // 信息提示条为"服务器程序"Shell_NotifyIcon(NIM_ADD, &m_nid); // 在托盘区添加图标4.重载对话框程序的WM_SIZE消息void CMediaPlayerDlg::OnSize(UINT nType, int cx, int cy){CDialog::OnSize(nType, cx, cy);// TODO: Add your message handler code hereif(nType == SIZE_MINIMIZED){ShowWindow(SW_HIDE); // 当最小化时,隐藏主窗口}}5.重载WM_DESTROY消息,关闭程序时关闭托盘上的程序图标void CMediaPlayerDlg::OnDestroy(){CDialog::OnDestroy();// TODO: Add your message handler code here// 系统关闭时在托盘区删除图标Shell_NotifyIcon(NIM_DELETE, &m_nid);// return CDialog::DestroyWindow();}。
VB实现窗口最小化到任务栏
要实现窗口最小化必须满足以下条件:1:按下最小化按钮,窗体不可见2:最小化后,最小化窗体的图标必须出现在任务栏的通知区域中3:当双击通知区域中的图标时,窗体又显示出来,同时通知区域中的图标消失.要满足上面的条件:1:首先屏蔽窗体中系统自带的最小化图标,即Form.MinButton=False2:声明1个API函数:Public Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias " Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDA TA) As Long注意:上面这个API函数在XP中没有别名,将别名去掉后为:Public Declare Function Shell_NotifyIcon Lib "shell32.dll"(ByVal dwMessage As Long, lpData As NOTIFYICONDA TA) As Long3:声明7个常数:Public Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const NIF_ICON = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_TIP = &H4Public Const WM_MOUSEMOVE = &H200Public Const WM_LBUTTONDBLCLK = &H2034:定义1个NOTIFYICONDA TA类型Public Type NOTIFYICONDATAcbSize as LonghWnd as LonguId as LonguFlags as LonguCallBackMessage as LonghIcon as LongszTip as StringEnd Type5:声明一个nid的类型Public nid as NOTIFYICONDA TA思路清晰后,开始编写代码1:在窗体中画1个Command,它的Caption属性为:"最小化"2:将窗体Form的MinButton的属性设为:"False"3:在窗体中添加1个模块,模块中的代码为:Public Declare Function Shell_NotifyIcon Lib "shell32.dll"(ByVal dwMessage As Long, lpData As NOTIFYICONDA TA) As LongPublic Const NIM_ADD = &H0Public Const NIM_DELETE = &H2Public Const NIF_ICON = &H2Public Const NIF_MESSAGE = &H1Public Const NIF_TIP = &H4Public Const WM_MOUSEMOVE = &H200Public Const WM_LBUTTONDBLCLK = &H203Public Type NOTIFYICONDATAcbSize as LonghWnd as LonguId as LonguFlags as LonguCallBackMessage as LonghIcon as LongszTip as StringEnd TypePublic nid as NOTIFYICONDA TA4:编写Command的单击事件:Private Sub Command1_Click()nid.cbSize = Len(nid)nid.uId = vbNullnid.hWnd = Me.hWndnid.uFlags = NIF_TIP Or NIF_MESSAGE Or NIF_ICONnid.uCallBackMessage = WM_MOUSEMOVEnid.hIcon = Me.Iconnid.szTip = "窗体最小化"Shell_NotifyIcon NIM_ADD, nidMe.HideEnd Sub5:编写窗体的MouseMove事件:Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single) Dim msg As Longmsg = X / 15If msg = WM_LBUTTONDBLCLK ThenMe.ShowShell_NotifyIcon NIM_DELETE, nidEnd IfEnd Sub按F5启动,单击Command,看看通知区域中是不是多了个窗体的图标?双击该图标,窗体又显示出来了!如何做到当我们单击窗口的最小化按钮时,窗口先最小化到任务栏成为按钮,然后消失,图标显示到通知栏呢?大家熟悉的FoxMail能做到,我们也可以做到。
vb将程序最小化到托盘
Public Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As LongPublic Declare Function DrawIcon Lib "user32" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal hicon As Long) As LongPublic Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As LongPublic Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long Public Declare Function TrackPopupMenu Lib "user32" (ByVal hMenu As Long, ByVal wFlags As Long, ByVal x As Long, ByVal y As Long, ByVal nReserved As Long, ByVal hwnd As Long, lprc As Any) As LongPublic Declare Function GetMenu Lib "user32" (ByVal hwnd As Long) As LongPublic Declare Function GetSubMenu Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As LongPublic Type POINTAPIx As Longy As LongEnd TypePublic Type NOTIFYICONDATAcbSize As Long '结构的长度hwnd As Long '消息接收窗口的句柄uID As Long '图标的标识uFlags As Long '设置参数uCallbackMessage As Long '回调消息的值hicon As Long '图标句柄szTip As String * 64 '提示字符串End TypePublic Const NIM_ADD = 0 '添加图标Public Const NIM_MODIFY = 1 '修改图标Public Const NIM_DELETE = 2 '删除图标Public Const NIF_MESSAGE = 1 '当有鼠标事件发生时产生消息Public Const NIF_ICON = 2 'Public Const NIF_TIP = 4 '图标有提示字符串Public Const WM_LBUTTONDOWN = &H201Public Const WM_RBUTTONDOWN = &H204Public Const WM_USER = &H400Public Const WM_NOTIFYICON = WM_USER + &H100Public Const WM_COMMAND = &H111Public Const WM_DESTROY = &H2Public Const WM_DRA WITEM = &H2BPublic Const WM_INITDIALOG = &H110Public Const WM_PAINT = &HFPublic Const WM_MENUSELECT = &H11FPublic Const GWL_WNDPROC = (-4) '替换窗口处理函数Dim pmenu As LongDim submenu As LongGlobal lproc As LongFunction CMenu() As Boolean'这个函数获得Form1的子菜单Dim l As LongDim l1 As Longpmenu = GetMenu(Form1.hwnd)submenu = GetSubMenu(pmenu, 0)If submenu ThenCMenu = TrueElseCMenu = FalseEnd IfEnd FunctionFunction Icon_Del(ihwnd As Long) As LongDim ano As NOTIFYICONDATADim l As Longano.hwnd = ihwndano.uID = 0ano.cbSize = Len(ano)'删除图标Icon_Del = Shell_NotifyIcon(NIM_DELETE, ano)End Function'这个函数接收图标句柄和窗口句柄并且新建图标Function Icon_Add(ihwnd As Long, hicon As Long) As LongDim ano As NOTIFYICONDATADim astr As String'为图标添加提示行astr = LTrim$(InputBox$("Input the tips you wanted to add.")) ano.szTip = astr + Chr$(0)'设置消息接收窗口ano.hwnd = ihwndano.uID = 0'图标有提示并且可以发送消息ano.uFlags = NIF_ICON Or NIF_TIP Or NIF_MESSAGEano.hicon = hiconano.cbSize = Len(ano)'将图标的回调消息设置为WM_NOTIFYICON,当在图标区域有鼠标消息,系统就会向'消息接收窗口发送WM_NOTIFYICON消息。
程序最小化到托盘
{
if(wParam!=IDR_MAINFRAME)
return 1;
switch(lParam)
{
case WM_RBUTTONUP://右键起来时弹出快捷菜单,这里只有一个“关闭”
delete lpoint;
}
break;
case WM_LBUTTONDBLCLK://双击左键的处理
{
this->ShowWindow(SW_SHOW);//简单的显示主窗口完事儿
}
2、程序已经最小化到托盘区了,但是对托盘图标的操作如何进行呢?这就体现了结构NOTIFYICONDATA的成员uCallbackMessage 的作用了。它所提供的作用就是,当用户用鼠标点击托盘区的图标的时候(无论是左键还是右键),会向hWnd所代表的窗口传送消息.
如上例,我们自定义了消息WM_SHOWTASK。根据VC的消息机制,对自定义消息增加消息响应函数.
然后在CPP文件中添加消息映射。在BEGIN_MESSAGE_MAP和END_MESSAGE_MAP 之间加入: ON_MESSAGE(WM_SHOWTASK,onShowTask)将消息和消息响应函数映射起来。
然后就是在CPP文件中加入函数onShowTask的实现了:
LRESULT CTimeWakeDlg::onShowTask(WPARAM wParam,LPARAM lParam)
strcpy(nid.szTip,"计划任务提醒"); //信息提示条为“计划任务提醒”
Shell_NotifyIcon(NIM_ADD,&nid); //在托盘区添加图标
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用VB6.0实现将窗体最小化到系统托盘区
使用说明:共有两个方法,经个人实际测试(环境:xpsp3 vb6.0)第二个控件法最有效果,第一个方法在启动时确实在右下角,但是弹出后再次最小化就跑到屏幕左下角了,无法最小化,不知道是啥原因,希望大家改进代码。
本人力荐第二种小巧有效简单的方法。
方法一
托盘,亦即程序最小化后程序图标隐藏到屏幕右下角的任务栏里。
这种最小化方法比普通的最小化节约空间,因此备受欢迎,很多软件都具有这样的功能。
在VB中,可用API 函数来实现托盘功能,但比较复杂,不太好操作。
相对而言采用一种非常简单易行的方法:控件法,才是最适合最方便的。
下面要使用已被微软封装好的控件:csystray1(名称可自定)。
说到控件,大家可能要皱眉头了:去哪找呀?放心!这个控件就躺在你的VB安装盘里(目录为:COMMON\TOOLS\VB\UNSUPPRT\SYSTRAY)!不过,得处理一下:请在Tool 文件夹里查找一个名叫Systray的目录,将它拷贝到硬盘,用VB打开该目录下的工程,必要的话可作些改进(如更换图标、添加功能等),然后编译成ocx控件,可以随意命名。
为方便使用起见,最好编译到Windows\System目录下。
好了,现在我们就可以在我们的程序中使用此控件来轻松实现托盘功能了。
vb中添加控件的方法就不用我说了吧?
控件的属性和事件浅析:
该控件的InTray属性是用来设置是否显示在托盘中,True为显示在托盘,False为不显示;
该控件的TrayIcon属性是在托盘中显示的图标式样;
该控件的TrayTip属性是鼠标移动到该控件上面时,显示的提示文字;
该控件的重要事件是几个我们常用的鼠标事件:按下、放开、移动、双击,编程时就是利用这些事件达到在任务栏中控制程序的目的。
源代码如下:
'使程序最小化时显示到系统托盘
Private Sub Form_Resize()
If Me.WindowState = 1 Then '如程序为最小化则——
cSysTray1.InTray = True '隐藏到任务栏
Me.Visible = False '让程序界面不可见
End If
End Sub
'点击托盘图标后,让程序窗体显示出来
Private Sub CsysTray1_MouseDown(Button As Integer, Id As Long)
Me.WindowState = 0 '程序回复到Normal状态
Me.Visible = True '从任务栏中清除图标
cSysTray1.InTray = False '令程序界面可见
Me.setfocus
End Sub
方法二1、新建立一个VB6工程,将Form1的ShowInTaskBar属性设置为False
2、菜单:工程--添加模块按“打开”这样就添加了一个新模块,名为Module1,保存为Module1.bas
3、在Module1中写下如下代码:
Option Explicit
Public Const MAX_TOOLTIP As Integer = 64
Public Const NIF_ICON = &H2
Public Const NIF_MESSAGE = &H1
Public Const NIF_TIP = &H4
Public Const NIM_ADD = &H0
Public Const NIM_DELETE = &H2
Public Const WM_MOUSEMOVE = &H200
Public Const WM_LBUTTONDOWN = &H201
Public Const WM_LBUTTONUP = &H202
Public Const WM_LBUTTONDBLCLK = &H203
Public Const WM_RBUTTONDOWN = &H204
Public Const WM_RBUTTONUP = &H205
Public Const WM_RBUTTONDBLCLK = &H206
Public Const SW_RESTORE = 9
Public Const SW_HIDE = 0
Public nfIconData As NOTIFYICONDATA
Public Type NOTIFYICONDATA
cbSize As Long
hWnd As Long
uID As Long
uFlags As Long
uCallbackMessage As Long
hIcon As Long
szTip As String * MAX_TOOLTIP
End Type
Public Declare Function ShowWindow Lib "user32" (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
Public Declare Function Shell_NotifyIcon Lib "shell32.dll" Alias "Shell_NotifyIconA" (ByVal dwMessage As Long, lpData As NOTIFYICONDATA) As Long
'4、在Form1的Load事件中写下如下代码:
Private Sub Form_Load()
'以下把程序放入System Tray====================================System Tray Begin
With nfIconData
.hWnd = Me.hWnd
.uID = Me.Icon
.uFlags = NIF_ICON Or NIF_MESSAGE Or NIF_TIP
.uCallbackMessage = WM_MOUSEMOVE
.hIcon = Me.Icon.Handle
'定义鼠标移动到托盘上时显示的Tip
.szTip = App.Title + "(版本" & App.Major & "." & App.Minor & "." & App.Revision & ")" & vbNullChar
.cbSize = Len(nfIconData)
End With
Call Shell_NotifyIcon(NIM_ADD, nfIconData)
'=============================================================System Tray End
Me.Hide
End Sub
'5、在Form1的QueryUnload事件中写入如下代码:
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
Call Shell_NotifyIcon(NIM_DELETE, nfIconData)
End Sub
'6、在Form1的MouseMove事件中写下如下代码:
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim lMsg As Single
lMsg = X / Screen.TwipsPerPixelX
Select Case lMsg
Case WM_LBUTTONUP
'MsgBox "请用鼠标右键点击图标!", vbInformation, "实时播音专家"
'单击左键,显示窗体
ShowWindow Me.hWnd, SW_RESTORE
'下面两句的目的是把窗口显示在窗口最顶层
'Me.Show
'Me.SetFocus
'' Case WM_RBUTTONUP
'' PopupMenu MenuTray '如果是在系统Tray图标上点右键,则弹出菜单MenuTray
'' Case WM_MOUSEMOVE
'' Case WM_LBUTTONDOWN
'' Case WM_LBUTTONDBLCLK
'' Case WM_RBUTTONDOWN
'' Case WM_RBUTTONDBLCLK
'' Case Else
End Select
End Sub
7、现在将程序保存起来运行看看系统托盘处是否增加了一个本工程的图标。
单击此图标,Form1就自动弹出来了。
----------------------------------------------华丽丽的分割线---------------------------------------------------。