今天做一个服务的小程序,需要做到类似服务那样执行,但需要与用户进行交互。因此需要窗体打开即关闭。在托盘上显示一个图标。经测试,满足要求。不会出现窗体一闪而过的情况。近拟窗体一直没有打开过的样子。
步骤:
1.首先要把窗体的formborderstyle属性设置成none.这样做的目的是使窗体不显示大小等按钮。下一步好设置窗体的大小。
2.设置窗体的大小值 。
static void Main(string[] args)
{
MainForm form = new MainForm();
form.Size = new System.Drawing.Size(1,1);
Application.Run(form);
}
3.声明一个Timer和一个delegate
private delegate void delegateThisHide();
System.Threading.Timer timer;
4.用Timer 判断this.created的值然后去处理。代码如下:
public partial class MainForm : Form
{
private delegate void delegateThisHide();
System.Threading.Timer timer;
public MainForm()
{
InitializeComponent();
Initiale();
}
private void Initiale()
{
NotifyIcon notify = new NotifyIcon();
notify.Icon = new System.Drawing.Icon(@".\Images\companyLOGO.ico");
notify.Text = "质检单服务程序";
ContextMenu menu = new ContextMenu();
MenuItem mexit = new MenuItem();
mexit.Index = 0;
mexit.Text = "退出";
mexit.Click += ExitProgram;
menu.MenuItems.Add(mexit);
notify.ContextMenu = menu;
notify.Visible = true;
timer = new System.Threading.Timer(hideThisForm, null, 10, 500);
//this.Hide();
}
private void ExitProgram(object sender, EventArgs e)
{
this.Close();
}
private void hideThisForm(object o)
{
if (this.Created)
{
this.Invoke(new delegateThisHide(hideform));
timer.Dispose();
}
}
private void hideform()
{
this.Hide();
}
}