コード例 #1
0
 internal ChannelImpl(String channelName)
 {
     this.channelName     = channelName;
     this.commandListener = new ChannelImpl.ChannelCommandListener(this);
     this.connectListener = new ChannelImpl.ChannelConnectListener(this, channelName);
     Join();
 }
コード例 #2
0
    public IDisposable AddListener(string cmd, int amountToTrigger, Action callback, bool loop = false)
    {
        CommandListener listener = new CommandListener(cmd, amountToTrigger, callback, loop);

        commandListeners.Add(listener);
        return(listener);
    }
コード例 #3
0
ファイル: Interpreter.cs プロジェクト: addi-sp-sp-4/SOGLang
        public static object interpret(string query)
        {
            IParseTree tree;
            string     querynospaces = query.Replace(" ", "");

            if (parseTrees.ContainsKey(querynospaces))
            {
                tree = parseTrees[querynospaces];
            }
            else
            {
                AntlrInputStream  inputStream       = new AntlrInputStream(query);
                LanguageLexer     lexer             = new LanguageLexer(inputStream);
                CommonTokenStream commonTokenStream = new CommonTokenStream(lexer);
                LanguageParser    parser            = new LanguageParser(commonTokenStream);
                parser.BuildParseTree = true;

                parser.AddErrorListener(new CommandErrorListener());

                tree = parser.command();
                parseTrees[querynospaces] = tree;
            }

            ParseTreeWalker walker = new ParseTreeWalker();

            CommandListener listener = new CommandListener();


            walker.Walk(listener, tree);

            return(listener.result);
        }
コード例 #4
0
        public void CommandListenerConstructorTest()
        {
            var methodCommandInfo = new MethodCommandInfo(null, null, null, null, "queue");
            var target            = new CommandListener(methodCommandInfo);

            Assert.AreEqual("queue", target.QueueName);
        }
コード例 #5
0
        public Thermometer()
        {
            InitializeComponent();

            var listener = new CommandListener("192.168.10.74", 8001);

            listener.OnNewCommandRecieved += listener_OnNewCommandRecieved;
        }
コード例 #6
0
ファイル: BotManager.cs プロジェクト: Trainfire/DogBot
        protected override void OnInitialize()
        {
            base.OnInitialize();

            CommandListener.AddCommand("!~adduser", AddUser, true);
            CommandListener.AddCommand("!~removeuser", RemoveUser, true);
            CommandListener.AddCommand("!~setname", SetName, true);
        }
コード例 #7
0
        public void AddCommand(string name, CommandListener listener)
        {
            if (_commands.ContainsKey(name))
            {
                throw new ArgumentException("Имя для команды уже занято");
            }

            _commands.Add(name, listener);
        }
コード例 #8
0
        public ApplicationDbContext(DbContextOptions <ApplicationDbContext> options)
            : base(options)
        {
            _adapter = new CommandListener();

            var listener = this.GetService <DiagnosticSource>();

            (listener as DiagnosticListener).SubscribeWithAdapter(_adapter);
        }
コード例 #9
0
        public IDisposable RegisterCommandListener(Action <ConsoleCommand> callback)
        {
            var listener = new CommandListener {
                Callback = callback, DisposeAction = UnregisterCommandListener
            };

            this.commandListeners.Add(listener);
            return(listener);
        }
コード例 #10
0
        static void Main(string[] args)
        {
            disableConsoleClosing();
            GameContext     context  = new GameContext();
            CommandListener listener = new CommandListener(context);

            MessagePump.Run(context.MainWindow, context.Render);
            listener.Dispose();
            context.Dispose();
        }
コード例 #11
0
        public void MemoryLeak()
        {
            var command  = new ManualRelayCommand(() => { }, () => true);
            var listener = new CommandListener();
            var wr       = new WeakReference(listener);

            command.CanExecuteChanged += listener.React;
            listener = null;
            GC.Collect();
            Assert.IsFalse(wr.IsAlive);
            command.CanExecute(); // Touching it after to prevent GC
        }
コード例 #12
0
ファイル: MainViewModel.cs プロジェクト: elnomade/speechy
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            ////if (IsInDesignMode)
            ////{
            ////    // Code runs in Blend --> create design time data.
            ////}
            ////else
            ////{
            ////    // Code runs "for real"
            ////}

            Log = new ObservableCollection<string>();
            Recognizers = SpeechEngineManager.Recognizers;
            SelectedRecognizer = Recognizers.Any() ? Recognizers.First() : null;

            Start = new RelayCommand(() =>
                {
                    if (listener != null && listener.Recognizer != SelectedRecognizer)
                    {
                        Stop.Execute(null);
                    }

                    listener = new CommandListener(SelectedRecognizer);
                    listener.LogEvent += listener_LogEvent;
                    listener.Start();

                    Log.Add("Started speech command listener " + SelectedRecognizer.Id);
                });

            Stop = new RelayCommand(() =>
                {
                    Log.Add("Stopping speech command listener " + listener.Recognizer.Id);

                    if (listener != null && listener.Recognizer != SelectedRecognizer)
                    {
                        listener.LogEvent -= listener_LogEvent;

                        listener.Dispose();
                        listener = null;
                    }
                    else
                    {
                        listener.Stop();
                    }
                });

            Speak = new RelayCommand(() =>
                {
                    SpeechSynthesizer synth = new SpeechSynthesizer();
                    synth.SetOutputToDefaultAudioDevice();
                    synth.Speak("Lorem ipsum dolor sit am.");
                });
        }
コード例 #13
0
 public ServerController()
 {
     CameraHeartbeat += async f => { await Task.Yield(); };
     _cameras         = new ConcurrentDictionary <string, RemoteCameraModel>(StringComparer.OrdinalIgnoreCase);
     _ping            = new PingUtility(50123);
     _sender          = new CommandSender();
     _listener        = new CommandListener();
     _listener.RegisterHandler <ReportingCommand, RemoteCameraModel>(HandleReporting);
     _uploader  = new UploadListener();
     _heartbeat = new HeartBeatListener();
     _heartbeat.DataRecieved += async f => { await CameraHeartbeat(f); };
 }
コード例 #14
0
 public ServerController()
 {
     CameraHeartbeat += async f => { await Task.Yield(); };
     _cameras = new ConcurrentDictionary<string, RemoteCameraModel>(StringComparer.OrdinalIgnoreCase);
     _ping = new PingUtility(50123);
     _sender = new CommandSender();
     _listener = new CommandListener();
     _listener.RegisterHandler<ReportingCommand, RemoteCameraModel>(HandleReporting);
     _uploader = new UploadListener();
     _heartbeat = new HeartBeatListener();
     _heartbeat.DataRecieved += async f => { await CameraHeartbeat(f); };
 }
コード例 #15
0
ファイル: MapModule.cs プロジェクト: Trainfire/DogBot
        protected override void OnInitialize()
        {
            base.OnInitialize();

            mapList = new MapList(this);
            config  = new MapModuleConfig();

            CommandListener.AddCommand <MapAdd>(ADD);
            CommandListener.AddCommand <MapRemove>(DELETE);
            CommandListener.AddCommand <MapGet>(GET);
            CommandListener.AddCommand <MapUpdate>(UPDATE);
        }
コード例 #16
0
 public CameraClientRemoteControl(CameraClientViewModel model, ClientController camera)
 {
     _model = model;
     _camera = camera;
     _heartbeat = new HeartbeatTimer(() => Task.FromResult(0));
     _ping = new PingUtility(50123);
     _ping.HandlePing += ReportCamera;
     _listener = new CommandListener();
     _listener.RegisterHandler<RecordCommand, RecordCommand>(RemoteRecord);
     _listener.RegisterHandler<EnableHeartbeatCommand, EnableHeartbeatCommand>(EnableHeartbeat);
     _listener.RegisterHandler<UpdateResolutionCommand, RemoteResolutionModel>(UpdateResolution);
 }
コード例 #17
0
        public void MemoryLeak()
        {
            var command  = new ManualRelayCommand <int>(x => { }, x => true);
            var listener = new CommandListener();
            var wr       = new WeakReference(listener);

            command.CanExecuteChanged += listener.React;
            //// ReSharper disable once RedundantAssignment
            listener = null;
            GC.Collect();
            Assert.IsFalse(wr.IsAlive);
            command.CanExecute(0); // Touching it after to prevent GC
        }
コード例 #18
0
        public void DeclareQueueTest()
        {
            var commandReceiverMock = new Mock <ICommandReceiver>(MockBehavior.Strict);

            commandReceiverMock.Setup(m => m.DeclareCommandQueue()).Verifiable();

            var mock = new Mock <IBusContext <IConnection> >(MockBehavior.Strict);

            mock.Setup(m => m.CreateCommandReceiver("queue")).Returns(commandReceiverMock.Object);

            var methodCommandInfo = new MethodCommandInfo(null, null, null, null, "queue");
            var target            = new CommandListener(methodCommandInfo);

            target.DeclareQueue(mock.Object);
        }
コード例 #19
0
 public void AddListener(string command, CommandListener listener)
 {
     command = command.ToLower();
     if (Listeners.ContainsKey(command))
     {
         Listeners[command].Add(listener);
     }
     else
     {
         Listeners[command] = new List <CommandListener>()
         {
             listener
         }
     };
 }
コード例 #20
0
ファイル: Listener.cs プロジェクト: LyokoAPI/MiniLyoko3
        public Listener(MainPanel panel)
        {
            CommandOutput    = panel.CommandOutputBox;
            LogOutput        = panel.LogText;
            _commandListener = new CommandListener();

            _commandListener.AddCommand(new Xana());
            _commandListener.AddCommand(new LW());
            _commandListener.AddCommand(new Aelita());

            //Ensure Help command is always the last command to be added to the listener
            List <Command> commands = _commandListener.GetCommands();

            _commandListener.AddCommand(new Help(ref commands));
        }
コード例 #21
0
 void OnCommandRecieved(string cmd)
 {
     for (int i = 0; i < commandListeners.Count; i++)
     {
         CommandListener listener = commandListeners[i];
         if (!listener.Listens)
         {
             commandListeners.Remove(listener);
             continue;
         }
         if (listener.Command == cmd)
         {
             listener.CurrentAmount++;
         }
     }
 }
コード例 #22
0
        public static void MemoryLeak()
        {
#if DEBUG
            return;            // debugger keeps things alive.
#endif
#pragma warning disable CS0162 // Unreachable code detected
            var command = new ManualRelayCommand <int>(x => { }, x => true);
#pragma warning restore CS0162 // Unreachable code detected
            var listener = new CommandListener();
            var wr       = new WeakReference(listener);
            command.CanExecuteChanged += listener.React;
            //// ReSharper disable once RedundantAssignment
            listener = null;
            GC.Collect();
            Assert.IsFalse(wr.IsAlive);
            Assert.NotNull(command); // Touching it after to prevent GC
        }
コード例 #23
0
        // todo: сохранять логин/пароль юзеров в файле. Хватит текстового.
        // todo: хранить непрочитанные сообщения пользователя в файле. Пожалуй, с именем как имя пользователя. username@myServer

        private static void Main(string[] args)
        {
            Console.WriteLine("TcpServer Starting...");

            //MessageHandler.OnSaveUserCommand += CommandListener_OnSaveUserCommand;
            //
            //



            var commandListener = new CommandListener(HandleClientMessage);

            commandListener.Start();
            Console.WriteLine("TcpServer Started. Press any key to exit.");
            Console.ReadKey();
            commandListener.Stop();
        }
コード例 #24
0
        static void Main(string[] args)
        {
            var scaleFactor = GetScaleFactor();
            var fps         = GetFPS();
            var recorder    = new Recorder(scaleFactor, fps);

            recorder.Start(3000);

            var commandListener = new CommandListener();

            commandListener.Start(3001);
            commandListener.OnMouseDown = OnMouseDown;
            commandListener.OnMouseUp   = OnMouseUp;
            commandListener.ListenForCommands();

            Console.WriteLine("Server started! Listening for connections...");
            Console.ReadLine();
        }
コード例 #25
0
        public void TestNoCommandManager()
        {
            int             CanExecuteCalls = 0;
            CommandListener listener        = new CommandListener(() => CanExecuteCalls++);
            MyTest          test            = new MyTest();
            DelegateCommand command         = new DelegateCommand(test.DoWork, test.CanExecute, false);

            command.CanExecuteChanged += listener.OnCanExecuteChanged;

            CommandManager.InvalidateRequerySuggested();
            Dispatcher.CurrentDispatcher.DoEvents();
            command.Execute(null);
            Assert.AreEqual(1, test.ExecuteCalls);
            Assert.AreEqual(0, CanExecuteCalls);

            command.RaiseCanExecuteChanged();
            Assert.AreEqual(1, CanExecuteCalls);
        }
コード例 #26
0
ファイル: Program.cs プロジェクト: sam2/Pubstars2
        static void Main(string[] args)
        {
            Settings.InitDefaults();
            GameContext  context = null;
            StateMachine sm      = new StateMachine();

            LoggerFactory loggerFactory = new LoggerFactory();

            loggerFactory.AddProvider(new ConsoleLogger());
            loggerFactory.AddProvider(new FileLogger());

            sm.Init(new Init()).Wait();

            while (true)
            {
                IEnumerable <string> lastGamePlayers = context?.LoggedInPlayers
                                                       .Where(x => x.Team != HQMTeam.NoTeam)
                                                       .Select(x => x.Name) ?? new List <string>();

                context = new GameContext();

                Warden              warden          = new Warden(context);
                CommandListener     commandListener = new CommandListener();
                LoginHandler        loginHandler    = new LoginHandler(context, commandListener);
                SubstitutionHandler subHandler      = new SubstitutionHandler(context, commandListener);

                loginHandler.Init().Wait();

                sm.AddState(new WaitingForPlayers(context, warden));
                sm.AddState(new GameSetup(context, lastGamePlayers));
                sm.AddState(new Gameplay());
                sm.AddState(new EndGame(context, warden));

                while (!sm.Update().Result)
                {
                    Thread.Sleep(50);
                    loginHandler.HandleLogins();
                    subHandler.Update();
                    warden.Watch();
                }
                ;
            }
        }
コード例 #27
0
        public void Initialize()
        {
            _busProviderMock
            .Setup(b => b.BasicTopicBind(ReplyQueueName, It.Is(MatchingKey)));

            _busProviderMock
            .Setup(b => b.BasicPublish(It.Is(MatchingReplyEventMessage)));

            _busProviderMock
            .Setup(b => b.BasicAcknowledge(DeliveryTag, false));

            _busProviderMock
            .Setup(b => b.EnsureConnection());

            _sut = new CommandListener(_busProviderMock.Object, _callbackRegistryMock.Object);

            _callbackWaitHandle = new ManualResetEvent(false);
            _receivedParameter  = null;
        }
コード例 #28
0
        public void RegisterCommand(IPlugin plugin, string command, CommandListener listener)
        {
            if (_commands.ContainsKey(command))
            {
                throw new Exception("Command already assigned");
            }

            if (!_pluginListeners.TryGetValue(plugin, out var listeners))
            {
                listeners = new List <RegisteredListener>();
                _pluginListeners[plugin] = listeners;
            }

            listeners.Add(new RegisteredListener()
            {
                Listener = listener,
                Command  = command
            });
            _commands[command] = listener;
        }
コード例 #29
0
        public void StartListeningToCommandsTest()
        {
            var hostMock = new Mock <IMicroserviceHost>();

            hostMock.Setup(m => m.CreateInstanceOfType(typeof(TestClass))).Returns(new TestClass());

            var methodCommandInfo = new MethodCommandInfo(null, null, null, null, "queue");
            var target            = new CommandListener(methodCommandInfo);

            var commandReceiverMock = new Mock <ICommandReceiver>(MockBehavior.Strict);

            commandReceiverMock.Setup(m => m.DeclareCommandQueue()).Verifiable();
            commandReceiverMock.Setup(m => m.StartReceivingCommands(target.Handle));

            var iBusContextMock = new Mock <IBusContext <IConnection> >(MockBehavior.Strict);

            iBusContextMock.Setup(m => m.CreateCommandReceiver("queue")).Returns(commandReceiverMock.Object);

            target.DeclareQueue(iBusContextMock.Object);
            target.StartListening(hostMock.Object);
        }
コード例 #30
0
ファイル: DogOfTheDay.cs プロジェクト: Trainfire/DogBot
        void OnAnnounce(object sender, EventArgs e)
        {
            if (!Bot.Connection.Connected)
            {
                Logger.Warning("Bot is not connected. Announcement cancelled...");
                return;
            }

            if (AnnouncementMode == AnnouncementMode.Hourly)
            {
                Logger.Info("Moving to next dog in queue...");
                Data.MoveToNextDog();
            }

            // Post DoTD
            if (Data.HasDog)
            {
                Logger.Info("Posting announcement...");
                CommandListener.FireCommand(DOTD);
            }
        }
コード例 #31
0
ファイル: DogOfTheDay.cs プロジェクト: Trainfire/DogBot
        protected override void OnInitialize()
        {
            Config  = new Config();
            Data    = new Data(this);
            Strings = new Strings(this);

            // Set announcement mode
            AnnouncementMode = Config.Data.AnnouncementMode;

            // Create the announcer
            announcer               = new Announcer();
            announcer.Announce     += OnAnnounce;
            announcer.AllAnnounced += OnAllAnnouncements;

            // Make an announcement once every hour.
            for (int i = 0; i < 24; i++)
            {
                announcer.AddTime(i, 59, 59);
            }

            announcer.Start();

            Logger.Info("Announcements remaining for {0}: {1}", DateTime.Now.DayOfWeek.ToString(), announcer.AnnouncementsRemaining);

            CommandListener.AddCommand <GetDogOfTheDay>(DOTD);
            CommandListener.AddCommand <GetDogOfTheDayCount>("!dotdcount");
            CommandListener.AddCommand <Stats>("!dotdstats");
            CommandListener.AddCommand <SubmitDogOfTheDay>("!dotdsubmit");
            CommandListener.AddCommand("!dogrnd", GetRandomDog);

            CommandListener.AddCommand("!dogpost", Post, true);
            CommandListener.AddCommand("!dogmovenext", MoveNext, true);
            CommandListener.AddCommand("!dogmute", Mute, true);
            CommandListener.AddCommand("!dogunmute", Unmute, true);
            CommandListener.AddCommand("!dogsort", Sort, true);
            CommandListener.AddCommand("!dogqueue", QueueInfo, true);
            CommandListener.AddCommand("!dogpeek", Peek, true);
            CommandListener.AddCommand("!dogtoggle", ToggleAnnouncementMode, true);
        }
コード例 #32
0
ファイル: Start.cs プロジェクト: adanpack/ImpostorHQ-Requiem
        public ImpostorHqPlugin(ILogger <ImpostorHqPlugin> logger, IEventManager eventManager, IGameManager gameManager, IMessageWriterProvider messageWriterProvider, IClientManager clientManager)
        {
            ImpostorHqR.Extension.Api.Registry.Impostor.ClientManager         = clientManager;
            ImpostorHqR.Extension.Api.Registry.Impostor.EventManager          = eventManager;
            ImpostorHqR.Extension.Api.Registry.Impostor.GameManager           = gameManager;
            ImpostorHqR.Extension.Api.Registry.Impostor.Logger                = logger;
            ImpostorHqR.Extension.Api.Registry.Impostor.MessageWriterProvider = messageWriterProvider;

            ReusableStringBuilderPool.Initialize();
            LoggingManager.Initialize();
            ConfigurationLoader.LoadConfigs(typeof(ImpostorHqPlugin).Assembly);
            ServiceManager.Init();
            ImpostorEventListenerCreator.Initialize();
            CommandProcessor.Start();
            CommandListener.Start();
            HelpCommandRegister.Register();
            WebBinder.Bind();
            WebApiListener.Start();
            HttpServer.Start();
            ExtensionLoader.Initialize();
            ExtensionLoader.Start();
        }
コード例 #33
0
        public async Task HandleTest()
        {
            var methodCommandInfo = new MethodCommandInfo(typeof(TestClass),
                                                          typeof(TestClass).GetMethod("TestCalled"),
                                                          typeof(TestClass).GetMethod("TestCalled").GetParameters().First(),
                                                          typeof(TestClass).GetMethod("TestCalled").ReturnType,
                                                          "queue");
            var target = new CommandListener(methodCommandInfo);

            var hostMock = new Mock <IMicroserviceHost>(MockBehavior.Strict);

            hostMock.Setup(m => m.CreateInstanceOfType(typeof(TestClass))).Returns(new TestClass());

            var commandReceiverMock = new Mock <ICommandReceiver>(MockBehavior.Strict);

            commandReceiverMock.Setup(m => m.DeclareCommandQueue()).Verifiable();
            commandReceiverMock.Setup(m => m.StartReceivingCommands(target.Handle));

            var iBusContextMock = new Mock <IBusContext <IConnection> >(MockBehavior.Strict);

            iBusContextMock.Setup(m => m.CreateCommandReceiver("queue")).Returns(commandReceiverMock.Object);

            target.DeclareQueue(iBusContextMock.Object);
            target.StartListening(hostMock.Object);

            TestCommand command = new TestCommand()
            {
                Message = "message"
            };

            var message = new CommandRequestMessage(JsonConvert.SerializeObject(command), null);

            var result = await target.Handle(message);

            var objectResult = JsonConvert.DeserializeObject <TestCommand>(result.Message);

            Assert.AreEqual("Message2", objectResult.Message);
        }
コード例 #34
0
        /// <summary>
        /// The hook procedure for window messages generated by the FileOpenDialog
        /// </summary>
        /// <param name="hWnd">the handle of the window at which this message is targeted</param>
        /// <param name="msg">the message identifier</param>
        /// <param name="wParam">message-specific parameter data</param>
        /// <param name="lParam">mess-specific parameter data</param>
        /// <returns></returns>
        public IntPtr MyHookProc(IntPtr hWnd, UInt32 msg, Int32 wParam, Int32 lParam)
        {
            try
            {
                if (hWnd == IntPtr.Zero)
                    return IntPtr.Zero;

                switch (msg)
                {
                    // We're not interested in every possible message; just return a NULL for those we don't care about
                    default:
                        {
                            return IntPtr.Zero;
                        }
                    // WM_INITDIALOG - at this point the OpenFileDialog exists, so we pull the user-supplied control
                    // into the FileOpenDialog now, using the SetParent API.
                    case WM.INITDIALOG:
                        {

                            _hWndParent = User32.GetParent(hWnd);

                            //setting a bool for whether the OS is RTL (not the installed language of WLW)
                            IsRTL = (User32.GetWindowLong(_hWndParent, User32.GWL_EXSTYLE) & User32.WS_EX_LAYOUTRTL) > 0;

                            //account for large title bar, borders for adjusting control locations
                            TITLEBARINFO titleBarInfo = new TITLEBARINFO();
                            titleBarInfo.cbSize = (uint)Marshal.SizeOf(titleBarInfo);
                            if (!User32.GetTitleBarInfo(_hWndParent, ref titleBarInfo))
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                            }

                            WINDOWINFO info = new WINDOWINFO();
                            info.cbSize = (uint)Marshal.SizeOf(info);
                            if (!User32.GetWindowInfo(_hWndParent, ref info))
                            {
                                throw new Win32Exception(Marshal.GetLastWin32Error());
                            }

                            _extraWindowHeight = (titleBarInfo.rcTitleBar.bottom - titleBarInfo.rcTitleBar.top) + 2 * (int)info.cyWindowBorders;
                            _extraWindowWidth = 2 * (int)info.cxWindowBorders;

                            Rectangle rcClient = new Rectangle(0, 0, 0, 0);
                            // Get client rectangle of dialog
                            RECT rcTemp = new RECT();
                            User32.GetWindowRect(_hWndParent, ref rcTemp);
                            rcClient.X = rcTemp.left;
                            rcClient.Y = rcTemp.top;
                            rcClient.Width = rcTemp.Width;
                            rcClient.Height = rcTemp.Height + TABS_HEIGHT + BUTTONS_HEIGHT;
                            //make the dialog box bigger
                            User32.MoveWindow(_hWndParent, rcClient.Left, rcClient.Top, rcClient.Width, rcClient.Height, true);
                            //move all the controls down
                            AdjustControlLocations();
                            //top tab control
                            mainTabControl = new LightweightControlContainerControl();
                            User32.SetParent(mainTabControl.Handle, _hWndParent);
                            mainTabControl.Location = new Point(0, 0);
                            mainTabControl.Anchor = AnchorStyles.Left | AnchorStyles.Right;
                            mainTabControl.Size = new Size(rcClient.Width, TABS_HEIGHT);

                            tabs = new TabLightweightControl();
                            tabs.ColorizeBorder = false;
                            tabs.VirtualBounds = new Rectangle(0, 0, rcClient.Width, TABS_HEIGHT);
                            tabs.LightweightControlContainerControl = mainTabControl;
                            tabs.DrawSideAndBottomTabPageBorders = false;

                            InsertImageTabControl tabFromFile = new InsertImageTabControl();
                            tabFromFile.TabText = Res.Get(StringId.InsertImageInsertFromFile);
                            tabFromFile.TabBitmap = ResourceHelper.LoadAssemblyResourceBitmap("ImageInsertion.Images.TabInsertFromFile.png");
                            tabFromFile.BackColor = SystemColors.Control;
                            User32.SetParent(tabFromFile.Handle, _hWndParent);
                            tabs.SetTab(0, tabFromFile);

                            mainTabControl.BackColor = tabFromFile.ApplicationStyle.InactiveTabTopColor;

                            //now, add tabs for the other controls
                            int i = 1;
                            foreach (InsertImageSource imageSource in imageSources)
                            {
                                InsertImageTabControl tab = new InsertImageTabControl();
                                tab.TabText = imageSource.TabName;
                                tab.TabBitmap = imageSource.TabBitmap;
                                tab.BackColor = SystemColors.Control;
                                tabs.SetTab(i++, tab);
                            }

                            tabs.SelectedTabNumberChanged += new EventHandler(tabs_SelectedTabNumberChanged);

                            //set the keyboard hook for tab switching
                            tabKeyboardHook = new TabbingHookProc(tabs);
                            tabKeyboardHook.Install(_hWndParent);

                            //add other image source panels
                            _panelImage = new Panel();
                            _panelImage.Location = new Point(0, mainTabControl.Size.Height);
                            _panelImage.BorderStyle = BorderStyle.None;
                            _panelImage.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
                            _panelImage.Size = new Size(rcClient.Width, rcClient.Height - TABS_HEIGHT - BUTTONS_HEIGHT - _extraWindowHeight);
                            _panelImage.Visible = false;

                            User32.SetParent(_panelImage.Handle, _hWndParent);

                            //initalize the other sources
                            foreach (InsertImageSource source in imageSources)
                            {
                                source.Init(_panelImage.Width, _panelImage.Height);
                                Control c = source.ImageSelectionControls;
                                DisplayHelper.Scale(c);
                                foreach (Control childControl in c.Controls)
                                    DisplayHelper.Scale(childControl);
                            }
                            DisplayHelper.Scale(_panelImage);

                            //special cancel button
                            _buttonPanel = new Panel();
                            _buttonPanel.Location = new Point(rcClient.Width - (int)(0.5 * _extraWindowWidth) - _buttonPanel.Width, _panelImage.Bounds.Bottom);
                            _buttonPanel.Size = new Size(75, 23);
                            _buttonPanel.BorderStyle = BorderStyle.None;

                            _cancelButton = new Button();
                            _cancelButton.TextAlign = ContentAlignment.MiddleCenter;
                            if (BidiHelper.IsRightToLeft)
                                _cancelButton.RightToLeft = RightToLeft.Yes;
                            _cancelButton.Text = Res.Get(StringId.CancelButton);
                            _cancelButton.FlatStyle = FlatStyle.System;
                            _cancelButton.Location = new Point(0, 0);
                            _cancelButton.Size = new Size(75, 23);
                            _cancelButton.Click += new EventHandler(_cancelButton_Click);

                            _buttonPanel.Controls.Add(_cancelButton);

                            User32.SetParent(_buttonPanel.Handle, _hWndParent);

                            int origWidth = _cancelButton.Width;
                            string tmp = _cancelButton.Text;
                            _cancelButton.Text = Res.Get(StringId.InsertImageButton);
                            int newWidth = Math.Max(origWidth, DisplayHelper.MeasureButton(_cancelButton));
                            _cancelButton.Text = tmp;
                            newWidth = Math.Max(newWidth, DisplayHelper.MeasureButton(_cancelButton));

                            _buttonPanel.Width = _cancelButton.Width = newWidth;
                            int deltaX = newWidth - origWidth;
                            _buttonPanel.Left -= deltaX;

                            //fixing up button text and tab order
                            IntPtr hWndOpenButton = User32.GetDlgItem(_hWndParent, _OPEN_BUTTON_ID);
                            User32.SetWindowText(hWndOpenButton, Res.Get(StringId.InsertImageButton));

                            mainTabControl.InitFocusManager();
                            mainTabControl.AddFocusableControls(tabs.GetAccessibleControls());
                            foreach (InsertImageSource tabPage in imageSources)
                                mainTabControl.AddFocusableControl(tabPage.ImageSelectionControls);

                            state = STATE.FILE;

                            return IntPtr.Zero;
                        }

                    case WM.SIZE:
                        {
                            ManipulatePanels();
                            return IntPtr.Zero;
                        }
                    // WM_NOTIFY - we're only interested in the CDN_SELCHANGE notification message:
                    // we grab the currently-selected filename and copy it into the buffer
                    case WM.NOTIFY:
                        {
                            IntPtr ipNotify = new IntPtr(lParam);
                            OfNotify ofNot = (OfNotify)Marshal.PtrToStructure(ipNotify, typeof(OfNotify));
                            Int16 code = (short)ofNot.hdr.code;
                            if (code == CommonDlgNotification.SelChange)
                            {
                                UpdateChosenImage(false);
                                //CheckOptions(false);
                            }
                            else if (code == CommonDlgNotification.InitDone)
                            {
                                listener = new CommandListener(_hWndParent, this, (int)User32.GetDlgCtrlID(_cancelButton.Handle));
                            }
                            else if (code == CommonDlgNotification.FileOk)
                            {
                                // update the image path (need to do this if the user selected
                                // a file by simpliy typing in the filepath text box)
                                UpdateChosenImage(true);

                                // ok to insert
                                _insertFile = true;
                            }
                            else if ((code == CommonDlgNotification.FolderChange) && (state == STATE.WEB))
                            {
                                // If the user hits the OK button while there is no valid selection
                                // within the File panel, the file dialog sends a CommonDlgNotification.FolderChange
                                // We use this combined with other relevant state to trigger the closing
                                // of the Image dialog
                                HitOpen();
                            }
                            return IntPtr.Zero;
                        }
                }
            }
            catch (Exception ex)
            {
                UnexpectedErrorMessage.Show(ex);
                return new IntPtr(1);
            }
            finally
            {
                GC.KeepAlive(this);
            }
        }