Экран-заставка не возвращает фокус на главную форму

Я все. В настоящее время у меня проблема с фокусировкой при использовании заставки. Я использую VS2008 с .NET framework 2.0. Кроме того, я связал свой проект с VisualBasic.dll, так как я использую ApplicationServices для управления своим единственным экземпляром приложения и заставкой.

Вот фрагмент кода, упрощенный по сравнению с тем, что я пытался отладить.

namespace MyProject
{
    public class Bootstrap
    {
        /// <summary>
        /// Main entry point of the application. It creates a default 
        /// Configuration bean and then creates and show the MDI
        /// Container.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            // Creates a new App that manages the Single Instance background work
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            App myApp = new App();
            myApp.Run(args);
        }
    }

    public class App : WindowsFormsApplicationBase
    {
        public App()
            : base()
        {
            // Make this a single-instance application
            this.IsSingleInstance = true;
            this.EnableVisualStyles = true;

            // There are some other things available in the VB application model, for
            // instance the shutdown style:
            this.ShutdownStyle = Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses;

            // Add StartupNextInstance handler
            this.StartupNextInstance += new StartupNextInstanceEventHandler(this.SIApp_StartupNextInstance);
        }

        protected override void OnCreateSplashScreen()
        {
            this.SplashScreen = new MyMainForm();
            this.SplashScreen.StartPosition = FormStartPosition.CenterScreen;
        }
        protected override void OnCreateMainForm()
        {
            // Do your initialization here
            //...
            System.Threading.Thread.Sleep(5000);  // Test
            // Then create the main form, the splash screen will automatically close
            this.MainForm = new Form1();
        }
        /// <summary>
        /// This is called for additional instances. The application model will call this 
        /// function, and terminate the additional instance when this returns.
        /// </summary>
        /// <param name="eventArgs"></param>
        protected void SIApp_StartupNextInstance(object sender,
            StartupNextInstanceEventArgs eventArgs)
        {
            // Copy the arguments to a string array
            string[] args = new string[eventArgs.CommandLine.Count];
            eventArgs.CommandLine.CopyTo(args, 0);

            // Create an argument array for the Invoke method
            object[] parameters = new object[2];
            parameters[0] = this.MainForm;
            parameters[1] = args;

            // Need to use invoke to b/c this is being called from another thread.
            this.MainForm.Invoke(new MyMainForm.ProcessParametersDelegate(
                ((MyMainForm)this.MainForm).ProcessParameters),
                parameters);
        }
    }
}

Теперь происходит следующее: что, когда я запускаю приложение, экран-заставка отображается, как ожидалось, но когда он уничтожается, он не возвращает фокус основной форме (Form1 в тесте). MainForm просто мигает оранжевым на панели задач. Если я запускаю приложение из IDE (VS2008), фокус работает нормально. Я использую XP Pro. Кроме того, основная форма находится не поверх всех остальных окон. Если я закомментирую метод OnCreateSplashScreen (), приложение получает фокус нормально.

Чтобы проверить нормальное выполнение, я использую командную строку VS для запуска моего приложения. Я использую релизную версию своего проекта.

Есть идеи?

Изменить: Я также обрабатываю событие StartUpNextInstance, чтобы отправить аргументы командной строки в мою основную форму. В целях тестирования он был удален здесь.

Edit: Добавлен еще немного кода. Теперь у вас есть все возможности моей начальной загрузки.

8
задан Joel Coehoorn 17 April 2012 в 03:27
поделиться