在服务中创建的表单未显示

时间:2015-12-12 13:36:52

标签: c# winforms service

我在C#中创建了Service。我需要一个GUI来配置服务,所以我在我的解决方案中添加了一个WinForms项目。我的计划是在服务中创建表单并在OnStart()服务方法中显示。然而,它不会表现出来。 WriteEntry()的{​​{1}}方法都已触发,因此我的代码肯定会被处理。有谁知道我在这里做错了什么?

EventLog


public partial class UrlWatcherService : ServiceBase
{
    private UrlWatcherForm _urlwatcherform;
    private EventLog _eventLog;
    private string _eventLogName = "UrlWatcherEventLog";
    private string _eventLogSource = "UrlWatcherSource";

    public UrlWatcherService()
    {
        InitializeComponent();
        LoadVariables();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    private void LoadVariables()
    {
        _urlwatcherform = new UrlWatcherForm();
        _eventLog = new EventLog();
        CanPauseAndContinue = true;

        if (!EventLog.SourceExists(_eventLogSource))
            EventLog.CreateEventSource(_eventLogSource, _eventLogName);

        _eventLog.Source = _eventLogSource;
        _eventLog.Log = _eventLogName;
        _eventLog.WriteEntry("Url Watcher Log Created", EventLogEntryType.Information);
    }

    protected override void OnStart(string[] args)
    {
        _eventLog.WriteEntry("Url Watcher Service Started", EventLogEntryType.Information);
        _urlwatcherform.Show();
        _eventLog.WriteEntry("Url Watcher Form Created", EventLogEntryType.Information);
    }

    protected override void OnPause()
    {
        base.OnPause();
        _eventLog.WriteEntry("Url Watcher Service Paused", EventLogEntryType.Information);
    }

    protected override void OnContinue()
    {
        base.OnContinue();
        _eventLog.WriteEntry("Url Watcher Log Continued", EventLogEntryType.Information);
    }

    protected override void OnStop()
    {
        _eventLog.WriteEntry("Url Watcher Service Stopped", EventLogEntryType.Information);
    }
}

编辑:澄清一下,如果我调试它如下,表格显示。我可以让线程进入睡眠状态,但这不再让我与Form进行交互。但表格肯定表明,它只处于反应迟钝的状态。

public partial class UrlWatcherForm : Form
{
    public UrlWatcherForm()
    {
        InitializeComponent();
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {

    }

    private void UrlWatcherGui_Resize(object sender, EventArgs e)
    {
        if (FormWindowState.Minimized == WindowState)
            Hide();
    }

    private void UrlWatcherGui_FormClosing(object sender, FormClosingEventArgs e)
    {
        Hide();
        e.Cancel = true;
    }

    private void urlWatcherNofiyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        Show();
    }
}

1 个答案:

答案 0 :(得分:1)

好的,由于史蒂夫的暗示,我把项目分开了。我根据this MSDN article使用合并模块,而不是在服务项目中引用GUI,我将它们分开,以便我可以将它们的项目输出放在合并模块中。然后我将合并的模块添加到我的安装程序,现在我在安装后运行该服务,并能够从我的开始菜单调用该表单。这不是我最初想要的,而是一个非常合理的选择。

感谢史蒂夫提示。