我有一个在无限循环中运行的小应用程序,并观察一个目录并打印其中是否有任何文件。我想在系统托盘中运行它,但是当我用鼠标右键单击图标时,什么也没有发生,但是当目标目录中有文件并且我的计算机开始打印时,菜单正在购物。
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Drawing.Printing;
using System.Text;
namespace CreativeGastPrint
{
public class SysTrayApp : Form
{
[STAThread]
public static void Main()
{
Application.Run(new SysTrayApp());
}
private NotifyIcon trayIcon;
private ContextMenu trayMenu;
public SysTrayApp()
{
trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Exit", OnExit);
trayIcon = new NotifyIcon();
trayIcon.Text = "PrintApp";
trayIcon.Icon = new Icon("cg.ico");
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
FileHandler handler = new FileHandler("C:\\print");
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
try
{
handler.FullDirList();
handler.FullContent();
List<FileInfo> temp = new List<FileInfo>();
foreach (FileInfo f in handler.Files)
{
temp.Add(f);
}
foreach (FileInfo f in temp)
{
DirectoryInfo d = f.Directory;
String content = System.IO.File.ReadAllText(f.FullName, Encoding.UTF8);
Printer printer = new Printer(content);
printer.PrintController = new StandardPrintController();
List<String> installed = new List<String>();
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
installed.Add(PrinterSettings.InstalledPrinters[i]);
}
if (installed.Contains(d.Name))
{
printer.PrinterSettings.PrinterName = d.Name;
}
printer.Print();
}
handler.DeleteFiles();
System.Threading.Thread.Sleep(2000);
stopwatch.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
}
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
base.OnLoad(e);
}
private void OnExit(object sender, EventArgs e)
{
Application.Exit();
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
// Release the icon resource.
trayIcon.Dispose();
}
base.Dispose(isDisposing);
}
}
}