Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

c# - Restoring window from the system tray when allowing only one instance of that program

ok, the title is pretty long and should tell the problem i'm facing with.

Here is the code when minimizing to icon tray:

void MainFormResize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.ShowInTaskbar = false;
            }
        }

When the program is already opened and in sys tray, and still someone wants to open another instance of it, then:

    private static void Main(string[] args)
            {
                bool createdNew = true;
                using (Mutex mutex = new Mutex(true, "IPADcommunicator", out createdNew))
                {
                    if (createdNew)
                    {
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new MainForm());
                    }
                    else
                    {
                        Process current = Process.GetCurrentProcess();
                        foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                        {
                            if (process.Id != current.Id)
                            {
                                IntPtr handle = FindWindow(null,"IPADcommunicator");
                                SetForegroundWindow(handle);
                                ShowWindow(handle,5);

                                break;
                            }
                        }
...

Howeve, it is not working properly. The mainwindow is not restored. I've googled a lot and haven't found solutions for that problem. Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Calling SetForegroundWindow() on an invisible window isn't going to work. There are many other possible failure mode, FindWindow() is a miserable one when you start passing null.

Don't invent this yourself, .NET already has great built-in support for single instance apps. You can even get a notification when a 2nd copy starts and pass the command line. Which is what you want here, simply restore the window instead of hacking the API. The code you need is here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...