Как запустить мьютекс-код в c # .net при событии нажатия кнопки? - PullRequest
1 голос
/ 03 февраля 2010

Это мой код, который я пытался запустить в моей программе на c # .net 3.5, но получаю ошибки.Что я делаю не так?

ошибка CS0115: 'Form1.Dispose (bool)': не найден подходящий метод для переопределения

Это код, где я получилошибка:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOption = null;
        this._poolGroup = null;
        this.close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

Фактическое кодирование начинается здесь:

Program.cs:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using PU;

namespace WindowsApplication1
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            // If this program is already running, set focus
            // to that instance and quit.
            if (ProcessUtils.ThisProcessIsAlreadyRunning())
            {
                // "Form1" is the caption (Text property) of the main form.
                ProcessUtils.SetFocusToPreviousInstance("Form1");
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
    }
}

ProcessUtils.cs:

using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace PU
{
    /// Summary description for ProcessUtils.
    public static class ProcessUtils
    {
        private static Mutex mutex = null;

        /// Determine if the current process is already running
        public static bool ThisProcessIsAlreadyRunning()
        {
            // Only want to call this method once, at startup.
            Debug.Assert(mutex == null);

            // createdNew needs to be false in .Net 2.0, otherwise, if another     instance of
            // this program is running, the Mutex constructor will block, and then throw 
            // an exception if the other instance is shut down.
            bool createdNew = false;

            mutex = new Mutex(false, Application.ProductName, out createdNew);

            Debug.Assert(mutex != null);

            return !createdNew;
        }

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool IsIconic(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        const int SW_RESTORE = 9;

        [DllImport("user32.dll")]
        static extern IntPtr GetLastActivePopup(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool IsWindowEnabled(IntPtr hWnd);

        /// Set focus to the previous instance of the specified program.
        public static void SetFocusToPreviousInstance(string windowCaption)
        {
            // Look for previous instance of this program.
            IntPtr hWnd = FindWindow(null, windowCaption);

            // If a previous instance of this program was found...
            if (hWnd != null)
            {
                // Is it displaying a popup window?
                IntPtr hPopupWnd = GetLastActivePopup(hWnd);

                // If so, set focus to the popup window. Otherwise set focus
                // to the program's main window.
                if (hPopupWnd != null && IsWindowEnabled(hPopupWnd))
                {
                    hWnd = hPopupWnd;
                }

                SetForegroundWindow(hWnd);

                // If program is minimized, restore it.
                if (IsIconic(hWnd))
                {
                    ShowWindow(hWnd, SW_RESTORE);
                }
            }
        }
    }

Ответы [ 2 ]

0 голосов
/ 08 февраля 2010

По умолчанию в Windows Form (в пространстве имен System.Windows.Forms) реализован IDisposable (в пространстве имен System)

Но из сообщения об ошибке похоже, что ваша «Form1» не расширяет класс «Form». Следовательно, в вашем коде компилятор жалуется на отсутствие «чрезмерно читаемого» метода.

Не могли бы вы также опубликовать свой код Form1?

0 голосов
/ 03 февраля 2010

Создайте свой мьютекс с true в качестве первого параметра.

И вставьте

if(!createdNew)
    mutex.Close();

перед

return !createdNew;
...