我有一个小应用程序在无限循环中运行并观察目录并在其中有任何文件时打印。我想在系统托盘中运行它,但是当我用鼠标右键单击图标时,没有任何反应,但是当目标目录中有文件并且我的计算机开始打印时,菜单就会出现。
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);
}
}
}
答案 0 :(得分:2)
一个在无限循环中运行的小应用程序
这是您的问题,while(true) { ... }
循环阻止处理Windows消息。这使你的应用程序失明和聋。
快速而非常脏的修复方法是在Application.DoEvents()
之后添加Sleep()
来电,但这不是正确的方法。当循环仍在运行时,您的OnExit()
可能会发生......
Windows是一个事件驱动的操作系统,因此编写事件驱动的解决方案。不使用Sleep()
或DoEvents()
。
在您的情况下,您可能应该使用Timer,可能还有BackgroundWorker或其他Thread解决方案。