110,539
社区成员
发帖
与我相关
我的任务
分享
//点击窗体的关闭按钮时,不关闭程序,而是最小化到系统托盘
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.notifyIcon1.Visible = true;
this.Hide();
e.Cancel = true;
}
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication2
{
static class Program
{
private static string strAppConstName = "WindowsFormsApplication2";
private static string strProcessName = "WindowsFormsApplication2";
//防止程序多次运行
private static Mutex mutexObject;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
//取得当前系统的版本
OperatingSystem os = Environment.OSVersion;
if ((os.Platform == PlatformID.Win32NT) && (os.Version.Major >= 5))
{
strAppConstName = @"Global\" + strAppConstName;
}
try
{
mutexObject = new Mutex(false, strAppConstName);
}
catch (ApplicationException e)
{
return;
}
//第一次运行
if (mutexObject.WaitOne(0, false))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run( new Form1());
mutexObject.ReleaseMutex();
}
else //当再次运行后 弹出已运行程序的主窗口
{
Process prevProcess = GetPreviousProcess();
//当程序最小化到系统托盘后,这个条件就为假了。不执
//行WakeupWindow(prevProcess.MainWindowHandle);
//如果在else里也执行WakeupWindow(prevProcess.MainWindowHandle);主窗口也弹不出来。好像是
//prevProcess.MainWindowHandle 为零了
if ((prevProcess != null) &&(prevProcess.MainWindowHandle != IntPtr.Zero))
{
WakeupWindow(prevProcess.MainWindowHandle);
}
else
{
//
MessageBox.Show("已经运行,并驻留在任务托盘。", "");
// WakeupWindow(prevProcess.MainWindowHandle);
}
}
mutexObject.Close();
}
public static Process GetPreviousProcess()
{
Process curProcess = Process.GetCurrentProcess();
Process[] allProcesses = Process.GetProcessesByName(strProcessName);
System.Windows.Forms.MessageBox.Show(allProcesses.Length.ToString());
foreach (Process checkProcess in allProcesses)
{
if (checkProcess.Id != curProcess.Id)
{
if (String.Compare(checkProcess.MainModule.ModuleName,curProcess.MainModule.ModuleName, true) == 0)
{
return checkProcess;
}
}
}
return null;
}
public static void WakeupWindow(IntPtr hWnd)
{
if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}
SetForegroundWindow(hWnd);
}
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
private const int SW_RESTORE = 1;
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MoreView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.notifyIcon1.Visible = true;
this.Hide();
e.Cancel = true;
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
IntPtr mainWindowHandle = this.Handle;
try
{
lock (this)
{
API.WriteHandle(mainWindowHandle);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace MoreView
{
static class Program
{
private static string ProcessName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
private static string mutexName = "Local\\" + ProcessName;
private static Mutex mutex = null;
private static API api;
private static IntPtr mainWindowHandle = System.IntPtr.Zero;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
try
{
mutex = new Mutex(false, mutexName);
}
catch
{
Application.Exit();
}
if (mutex.WaitOne(0, false))
{
lock (typeof(Form1))
{
API.CreateMMF("Local" + "file://" + ProcessName, API.FileAccess.ReadWrite, 8);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
try
{
lock (typeof(Form1))
{
mainWindowHandle = API.ReadHandle("Local" + "file://" + ProcessName);
}
if (mainWindowHandle != IntPtr.Zero)
{
API.ShowWindow(mainWindowHandle, 1);
}
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace +
"\n\n" + "Application Exiting...", "Exception thrown");
}
GC.KeepAlive(mutex);
try
{
mutex.ReleaseMutex();
}
catch (ApplicationException ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace,
"Exception thrown");
GC.Collect();
}
}
}
}
}
using System;
using System.Runtime.InteropServices;
namespace MoreView
{
public class API
{
private const int INVALID_HANDLE_VALUE = -1;
private const int FILE_MAP_WRITE = 0x2;
private const int FILE_MAP_READ = 0x0004;
private static IntPtr memoryFileHandle;
[DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
public static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);
[DllImport("kernel32.dll", EntryPoint = "OpenFileMapping", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr OpenFileMapping(int wDesiredAccess, bool bInheritHandle, String lpName);
[DllImport("Kernel32.dll", EntryPoint = "CreateFileMapping", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr CreateFileMapping(int hFile, IntPtr lpAttributes, uint flProtect, uint dwMaximumSizeHigh, uint dwMaximumSizeLow, string lpName);
//hFile——要进行内存映射的文件句柄。当在系统页文件中创建MMF时,这个值必须是0xFFFFFFFF(-1)。
//lpAttributes——指向一个SECURITY_ATTRIBUTES结构体的指针
//flProtect——为内存映射文件指定的保护类型。
//PAGE_READONLY——只读访问。
//PAGE_READWRITE——读/写访问。
//PAGE_WRITECOPY——Copy-on-write访问。
//PAGE_EXECUTE_READ——读取和执行访问。
//PAGE_EXECUTE_READWRITE——读取、写入和执行访问。
//dwMaximumSizeHigh——文件映射对象的最大大小的DWORD值的高位。
//dwMaximumSizeLow——文件映射对象的最大大小的DWORD值的低位。
//lpName——文件映射对象的名字。
[DllImport("Kernel32.dll")]
public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
[DllImport("Kernel32.dll", EntryPoint = "UnmapViewOfFile", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport("kernel32.dll", EntryPoint = "CloseHandle", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool CloseHandle(uint hHandle);
public enum FileAccess : int
{
ReadOnly = 2,
ReadWrite = 4
}
/// <summary>
/// 创建共享内存
/// </summary>
/// <param name="fileName"></param>
/// <param name="access"></param>
/// <param name="size"></param>
/// <returns></returns>
public static void CreateMMF(string fileName, FileAccess access, int size)
{
if (size < 0)
throw new ArgumentException("The size parameter" +
" should be a number greater than Zero.");
memoryFileHandle = CreateFileMapping(-1,
IntPtr.Zero, (uint)access, 0, (uint)size, fileName);
if (memoryFileHandle == IntPtr.Zero)
throw new Exception("Creating Shared Memory failed.");
}
/// <summary>
/// 写共享内存
/// </summary>
/// <param name="windowHandle"></param>
public static void WriteHandle(IntPtr windowHandle)
{
IntPtr mappedViewHandle = MapViewOfFile(memoryFileHandle, (uint)FILE_MAP_WRITE, 0, 0, 8);
if (mappedViewHandle == IntPtr.Zero)
throw new Exception("Creating" +
" a view of Shared Memory failed.");
Marshal.WriteIntPtr(mappedViewHandle, windowHandle);
UnmapViewOfFile(mappedViewHandle);
CloseHandle((uint)mappedViewHandle);
}
/// <summary>
/// 读共享内存
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static IntPtr ReadHandle(string fileName)
{
IntPtr mappedFileHandle =
OpenFileMapping((int)FileAccess.ReadWrite, false, fileName);
if (mappedFileHandle == IntPtr.Zero)
throw new Exception("Opening the" +
" Shared Memory for Read failed.");
IntPtr mappedViewHandle = MapViewOfFile(mappedFileHandle,
(uint)FILE_MAP_READ, 0, 0, 8);
if (mappedViewHandle == IntPtr.Zero)
throw new Exception("Creating" +
" a view of Shared Memory failed.");
IntPtr windowHandle = Marshal.ReadIntPtr(mappedViewHandle);
if (windowHandle == IntPtr.Zero)
throw new ArgumentException("Reading from the specified" +
" address in Shared Memory failed.");
UnmapViewOfFile(mappedViewHandle);
CloseHandle((uint)mappedFileHandle);
return windowHandle;
}
}
}
static class Program
{
private static string strProcessName = "Form1" ;
private static string strAppName = "WindowsFormsApplication1";
static int hWnd = 0;
const int SW_SHOW = 5;
[DllImport("user32.dll", EntryPoint = "ShowWindow")]
public static extern int ShowWindow(int hwnd, int nCmdShow);
[DllImport("user32")]
public static extern int GetWindowText(int hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);
public delegate bool CallBack(int hWnd, int lParam);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Process[] ps = Process.GetProcessesByName(strAppName);
CallBack myCallBack = new CallBack(FineAppWindow);
EnumWindows(myCallBack, 0);
if (ps.Length > 1)
{
ShowWindow(hWnd, SW_SHOW);
return;
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public static bool FineAppWindow(int hwnd, int lParam)
{
StringBuilder sb = new StringBuilder(200);
int n = GetWindowText(hwnd, sb, 200);
if (sb.ToString() == strProcessName)
{
hWnd = hwnd;
}
return true;
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
this.WindowState = FormWindowState.Normal;
if(this.Visible == false)
this.Show();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.notifyIcon1.Visible = true;
this.Hide();
e.Cancel = true;
}
Private Sub NotifyIcon1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles NotifyIcon1.Click
If WindowState = FormWindowState.Minimized Then
WindowState = FormWindowState.Maximized
Activate()
NotifyIcon1.Visible = False
'ShowInTaskbar = True
自己需要的主頁面= True
End If
Sub