Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

System.Windows.UIElement.IsFocused' cannot be assigned to -- it is read only

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    System.Windows.UIElement.IsFocused' cannot be assigned to -- it is read only

    I'm getting this error
    NinjaScript File Error Code Line Column
    Testa.cs Property or indexer 'System.Windows.UIElement.IsFocused' cannot be assigned to -- it is read only CS0200 304 8
    From this line
    PHP Code:
    ChartControl.ChartPanels[0].IsFocused = true; 
    
    in this snippet
    PHP Code:
    protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
    {
      // FOCUS on Chart's Window
      TriggerCustomEvent(n =>
      {
        ChartControl.Dispatcher.InvokeAsync((Action)(() =>
        {
          if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
          {
            ChartControl.ChartPanels[0].IsFocused = true;
            ChartControl.ChartPanels[0].Focus();
            Print("0 : " + ChartControl.ChartPanels[0].IsFocused);
          }
        }));
    
      }, null);
      e.Handled = true; 
    
    While focused (after clicking on panel 0 with the mouse) on ChartControl.ChartPanels[0], it prints as true.
    0 : True

    I want to set ChartControl.ChartPanels[0].IsFocused to true when pressing Ctrl+Insert while the focus is on a Quantity Selector TextBox.
    The purpose is to shift the focus out of the Quantity Selector TextBox back to the Chart Panel.


    ChartControl.ChartPanels[0].Focus(); doesn't work.

    How can I enable
    ChartControl.ChartPanels[0].IsFocused = true; ? Thanks!

    #2
    Hello PaulMohn,

    Thank you for your post.

    We document the IsFocused property for ChartPanel, but we do not do so for ChartControl.

    I would take a look at this example from a post by one of my colleagues that demonstrates:

    Hi, I'm developing a "standalone" unmanaged strategy which has its own Winforms interface. Yes, I know about WPF but this older approach is, for me at least, an easier approach, and it's working fine. But since the strategy is started by, and associated with a NinjaTrader "host" Chart, and I'm wanting to use


    Please let us know if we may be of further assistance to you.

    Comment


      #3
      Hello Kate and many thanks for the direction and interesting fix from Jim.

      I just tested the following
      PHP Code:
      protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
      {
        // FOCUS on Chart's Window
        TriggerCustomEvent(n =>
        {
            if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
            {
              if (State == State.Historical)
                return;
      
            foreach (var window in NinjaTrader.Core.Globals.AllWindows)
            {
              // check if the found window is a Chart window, if not continue looking
              if (!(window is NinjaTrader.Gui.Chart.Chart)) continue;
      
              window.Dispatcher.InvokeAsync(new Action(() =>
              {
                // try to cast as a Chart, if it fails it will be null
                var foundChart = window as NinjaTrader.Gui.Chart.Chart;
      
                // make sure we found a chart
                if (foundChart == null) return;
      
                // make sure the found chart is the owner window
                if (foundChart == this.Owner as NinjaTrader.Gui.Chart.Chart)
                {
                  if (foundChart.ActiveChartControl.ChartPanels[ChartPanel.PanelIndex] == ChartPanel)
                  {
                  ClearOutputWindow();
      
                  foundChart.ActiveChartControl.ChartPanels[0].Focus();
                  Keyboard.Focus(foundChart.ActiveChartControl.Chart Panels[0]);
      
                  Print(ChartPanel.IsFocused.ToString());
                  Print(foundChart.ActiveChartControl.IsFocused);
                  Print(foundChart.ChartTrader.IsFocused);
                  Draw.TextFixed(this, "Status", ChartPanel.IsFocused.ToString(), TextPosition.BottomLeft);
                  }
                }
              }));
            }
            }
      
        }, null);
        e.Handled = true; 
      

      Nothing prints when focus is in the Quantity Selector TextBox.

      The Focus doesn't shift out of the Quantity Selector Textbox back into the ChartPanel.

      Also, nothing prints when focus is on the ChartPanel 0.

      Why doesn't it print?
      Why doesn't it work?
      What fix/next step would you suggest? Thanks!


      I printed the following
      PHP Code:
      protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
      {
        // FOCUS on Chart's Window
        TriggerCustomEvent(n =>
        {
            if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
            {
              Print("0 : " + ChartPanel.IsFocused.ToString());
      
              if (State == State.Historical)
              return;
      
              Print("1 : " + ChartPanel.IsFocused.ToString());
              foreach (var window in NinjaTrader.Core.Globals.AllWindows)
              {
              Print("2 : " + ChartPanel.IsFocused.ToString());
              // check if the found window is a Chart window, if not continue looking
              if (!(window is NinjaTrader.Gui.Chart.Chart)) continue;
      
              Print("3 : " + ChartPanel.IsFocused.ToString());
              window.Dispatcher.InvokeAsync(new Action(() =>
              {
              Print("4 : " + ChartPanel.IsFocused.ToString());
              // try to cast as a Chart, if it fails it will be null
              var foundChart = window as NinjaTrader.Gui.Chart.Chart;
      
              Print("5 : " + ChartPanel.IsFocused.ToString());
              // make sure we found a chart
              if (foundChart == null) return;
      
              Print("6 : " + ChartPanel.IsFocused.ToString());
              // make sure the found chart is the owner window
              if (foundChart == this.Owner as NinjaTrader.Gui.Chart.Chart)
              {
              Print("7 : " + ChartPanel.IsFocused.ToString());
                if (foundChart.ActiveChartControl.ChartPanels[ChartPanel.PanelIndex] == ChartPanel)
                {
              Print("8 : " + ChartPanel.IsFocused.ToString());
                ClearOutputWindow();
              Print("9 : " + ChartPanel.IsFocused.ToString());
      
                foundChart.ActiveChartControl.ChartPanels[0].Focus();
                Keyboard.Focus(foundChart.ActiveChartControl.Chart Panels[0]);
      
              Print("10 : " + ChartPanel.IsFocused.ToString());
                Print(ChartPanel.IsFocused.ToString());
                Print(foundChart.ActiveChartControl.IsFocused);
                Print(foundChart.ChartTrader.IsFocused);
                Draw.TextFixed(this, "Status", ChartPanel.IsFocused.ToString(), TextPosition.BottomLeft);
                }
              }
              }));
              }
            }
      
        }, null);
        e.Handled = true; 
      

      Result with focus on the ChartPanel 0

      0 : True
      1 : True
      2 : True
      2 : True
      2 : True
      3 : True
      2 : True
      4 : True
      5 : True
      6 : True
      Result with focus on the Quantity Selector TextBox is there's no prints.

      it seems the problematic line is
      PHP Code:
      if (foundChart == this.Owner as NinjaTrader.Gui.Chart.Chart) 
      

      What should I do next? Thanks!
      Last edited by PaulMohn; 06-10-2022, 12:41 PM.

      Comment


        #4
        Hello PaulMohn,

        Thank you for your reply.

        I've created a little better example from Jim's code sample in that post I linked. If you run this on, say, a 15 second chart, and put your mouse cursor in the Chart Trader quantity box, you should see that box get unselected when the bar closes, because the focus will shift to the ChartPanel.

        Here's an example of the output seen when that occurs:

        ChartPanel focused before: False
        foundChart.ActiveChartControl focused before: False
        foundChart.ChartTrader focused before: False
        ChartPanel focused: True
        foundChart.ActiveChartControl focused: False
        foundChart.ChartTrader focused: False

        So this just demonstrates that we are able to focus on the ChartPanel, but not ChartControl.

        Please let us know if we may be of further assistance to you.
        Attached Files

        Comment


          #5
          Thanks Kate for the test and sample.

          I did further tests. A short 2min demo

          Neither my Quantity Selector located in the Toolbar (1st test) nor the Quantity Selector located in the ChartTrader (2nd test) do focus out.
          Only when the cursor is clicked and focused on the Panel 0 does it print.
          And it prints true, but the cursor still remains in the quantity Selector box.

          For some reason only with the commented out following condition
          // if (foundChart == this.Owner as NinjaTrader.Gui.Chart.Chart)
          // {
          //}

          does it prints true.

          // FOCUS on Chart's Window
          TriggerCustomEvent(n =>
          {
          if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
          {
          Print("0 : " + ChartPanel.IsFocused.ToString());

          if (State == State.Historical)
          return;

          Print("1 : " + ChartPanel.IsFocused.ToString());
          foreach (var window in NinjaTrader.Core.Globals.AllWindows)
          {
          Print("2 : " + ChartPanel.IsFocused.ToString());
          // check if the found window is a Chart window, if not continue looking
          if (!(window is NinjaTrader.Gui.Chart.Chart)) continue;

          Print("3 : " + ChartPanel.IsFocused.ToString());
          window.Dispatcher.InvokeAsync(new Action(() =>
          {
          Print("4 : " + ChartPanel.IsFocused.ToString());
          // try to cast as a Chart, if it fails it will be null
          var foundChart = window as NinjaTrader.Gui.Chart.Chart;

          Print("5 : " + ChartPanel.IsFocused.ToString());
          // make sure we found a chart
          if (foundChart == null) return;

          Print("6 : " + ChartPanel.IsFocused.ToString());

          // make sure the found chart is the owner window
          // if (foundChart == this.Owner as NinjaTrader.Gui.Chart.Chart)
          // {


          Print("7 : " + ChartPanel.IsFocused.ToString());
          if (foundChart.ActiveChartControl.ChartPanels[ChartPanel.PanelIndex] == ChartPanel)
          {

          Print("8 : " + ChartPanel.IsFocused.ToString());
          Print("");
          Print("ChartPanel focused before: " + ChartPanel.IsFocused.ToString());
          Print("foundChart.ActiveChartControl focused before: " +foundChart.ActiveChartControl.IsFocused);
          Print("foundChart.ChartTrader focused before: " +foundChart.ChartTrader.IsFocused);
          //ClearOutputWindow();
          ChartPanel.Focus();
          foundChart.ActiveChartControl.ChartPanels[0].Focus();
          Keyboard.Focus(foundChart.ActiveChartControl.Chart Panels[0]);

          Print("ChartPanel focused: " + ChartPanel.IsFocused.ToString());
          Print("foundChart.ActiveChartControl focused: " +foundChart.ActiveChartControl.IsFocused);
          Print("foundChart.ChartTrader focused: " +foundChart.ChartTrader.IsFocused);
          Draw.TextFixed(this, "Status", ChartPanel.IsFocused.ToString(), TextPosition.BottomLeft);
          }
          // }
          }));
          }
          }

          }, null);
          e.Handled = true;

          Any idea what I'm missing?
          I don't understand why it would work in your OnBarUpdate method but not in my Ctrl+Insert hotkey.
          Would you like my indicator? Here's attached. lines 160-218 is the snippet.

          How can I get the cursor to leave the Quantity Selector Box when pressing Ctrl+Insert?
          I need it to trigger orders upon other Key Presses (NumPad1, numpad2, NumPad7, NumPad4, Ctral+NumPad7, Ctrl+NumPad4 etc.). Thanks!

          I changed the video to better quality
          Attached Files
          Last edited by PaulMohn; 06-11-2022, 05:17 AM. Reason: I changed the video to better quality

          Comment


            #6
            Hello Kate,

            I've just tested as well your
            FocusOnPanelExample.zip (1.8 KB, 1 view) indicator.

            Here's a short demo.

            As you can see nothing happens nor prints at the 15 seconds close.

            Do you get it to work on your end? Thanks!


            After new test it works on my end but same as before with commented out
            // if (foundChart == this.Owner as NinjaTrader.Gui.Chart.Chart)
            // {
            // }

            demo


            But it's still not working on my indicator even with commented out
            // if (foundChart == this.Owner as NinjaTrader.Gui.Chart.Chart)
            // {
            // }


            I'll test building it with PreviewKeyDown event from your indicator.

            I've tested your script with PreviewKeyDown Event added and it still doesn't work
            demo

            I tested both with ChartControl and ChartPanel used for the PreviewKeyDown method.

            The demo shows that the PreviewKeyDown event works when first focused on the Panel 0, but doesn't work when first focused in the ChartTrader quantity Selector box.

            Please find attached the modified scripts:
            FocusOnpanelExampletestChartPanel.zip
            FocusOnpanelExampletestChartControl.zip

            Thank you for your next tip or solution. Thanks!
            Attached Files
            Last edited by PaulMohn; 06-13-2022, 06:29 AM.

            Comment


              #7
              Hello PaulMohn,

              Thank you for your replies.

              As with these threads, unfortunately this would be outside the scope of what we could support - we've gone a little outside of that already. I would refer you to Jim and Jesse's comments on these threads, but we'd be unable to further troubleshoot.



              I'm wondering if that would be possible in someway I can't grasp yet. I'm trying to find a way to create a Hotkey that would: detect the QuantitySelector field, focus the cursor in it, and then fill it with a value and then focus the cursor out of the Quantity Selector field and focus it on the Chart I know how to do it


              Please let us know if we may be of further assistance to you.

              Comment


                #8
                Hello Kate and thanks for the reference. I was aware of those other threads that were directed at the ChartControl and I did pursue those suggestions but haven't been able to find a solution.

                I've tested Jesse's suggestion with Visual Studio but I don't know how to get all the sub-objects references. Do you have a Visual Studio demo on what to look for? Is it the correct way towards the solution? Why isn't the ChartControl.ChartPanels[0].Focus() enough if it can be focused and is documented as such?

                Can you please inform on what to do next as I'm not sure of what to do with the ChartPanel. I understand it does work with the OnBarUpdate method, but not with the PreviewKeyDown method. Why?

                I did the testings and it still doesn't make sense.

                Why does it focus with the OnbarUpdate but not with the PreviewKeyDown event? How can know? Thanks!


                I've copied the Visual Studio codes
                for
                demo

                Collections
                Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.

                ChartPanel
                Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.

                ChartControl
                Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.

                Chart
                Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.


                Supposing it is still relevant and still helpful for the ChartPanel issue, what would I need to look for? Thanks!

                If the solution is elsewhere/with other sub-objects, where would it be/what other sub-objects would it be? Thanks!

                I copied the UIElement Visual Studio Code
                Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.


                Here all the lines with focus
                PHP Code:
                23 public static readonly DependencyProperty IsKeyboardFocusedProperty;
                28 public static readonly DependencyProperty IsKeyboardFocusWithinProperty;
                59 public static readonly DependencyProperty FocusableProperty;
                64 public static readonly DependencyProperty IsFocusedProperty;
                66 public static readonly RoutedEvent LostFocusEvent;
                81 public static readonly RoutedEvent GotFocusEvent;
                121 public static readonly RoutedEvent LostKeyboardFocusEvent;
                122 public static readonly RoutedEvent PreviewLostKeyboardFocusEvent;
                123 public static readonly RoutedEvent GotKeyboardFocusEvent;
                124 public static readonly RoutedEvent PreviewGotKeyboardFocusEvent;
                151 public bool IsFocused { get; }
                168 public bool Focusable { get; set; }
                193 public bool IsKeyboardFocused { get; }
                198 public bool IsKeyboardFocusWithin { get; }
                204 protected internal virtual bool HasEffectiveKeyboardFocus { get; }
                243 public event DependencyPropertyChangedEventHandler FocusableChanged;
                247 public event RoutedEventHandler LostFocus;
                250 public event RoutedEventHandler GotFocus;
                251 public event DependencyPropertyChangedEventHandler IsKeyboardFocusedChanged;
                256 public event DependencyPropertyChangedEventHandler IsKeyboardFocusWithinChanged;
                263 public event KeyboardFocusChangedEventHandler LostKeyboardFocus;
                264 public event KeyboardFocusChangedEventHandler PreviewLostKeyboardFocus;
                265 public event KeyboardFocusChangedEventHandler GotKeyboardFocus;
                288 public event KeyboardFocusChangedEventHandler PreviewGotKeyboardFocus;
                330 public bool Focus();
                337 public virtual bool MoveFocus(TraversalRequest request);
                338 public virtual DependencyObject PredictFocus(FocusNavigationDirection direction);
                364 protected virtual void OnGotFocus(RoutedEventArgs e);
                365 protected virtual void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e);
                369 protected virtual void OnIsKeyboardFocusedChanged(DependencyPropertyChang edEventArgs e);
                370 protected virtual void OnIsKeyboardFocusWithinChanged(DependencyPropertyC hangedEventArgs e);
                379 protected virtual void OnLostFocus(RoutedEventArgs e);
                405 protected virtual void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEven tArgs e);
                408 protected virtual void OnPreviewLostKeyboardFocus(KeyboardFocusChangedEve ntArgs e); 
                

                Do you know if those are the sub-objects I need to test? If not what other Visual Studio "page" should I look at? Thanks!
                Last edited by PaulMohn; 06-13-2022, 02:26 PM.

                Comment


                  #9
                  New ideas.
                  I tested using the Tab key inside the Toolbar and the ChartTrader Quantity Selector box and it does move out of focus, but in spite of that when pressing orders hotkeys when out of the quantity Selector box it does just prompt for the Instrument selector/Timeframe period selector instead.
                  demo
                  That suggests it wouldn't be enough even shifting the focus.

                  Any idea on "disabling the Instrument selector/TimeFrame selector"? What method would I call (the opposite of this request)?
                  Last edited by PaulMohn; 06-13-2022, 03:57 PM.

                  Comment


                    #10
                    The simple solution was

                    1x Ctrl+Tab (for The ToolBar Quantity Selector)

                    PHP Code:
                    Ctrl+Tab 
                    
                    /
                    PHP Code:
                    System.Windows.Forms.SendKeys.SendWait("^{TAB}") ; 
                    

                    and / or

                    13x Ctrl+Shift+Tab (for The ChartTarader Quantity Selector)
                    PHP Code:
                    Ctrl+Shift+Tab 
                    

                    PHP Code:
                    for (int index = 0; index < 14; index++)
                    {
                       System.Windows.Forms.SendKeys.SendWait("^+{TAB}");
                    } 
                    

                    demo


                    I tested pressing a button without success
                    (the button gets pressed when focused 1st on the Chart Panel,
                    but it doesn't when 1st focused in the Quantity Selector Box)

                    Using declarations assemblies
                    PHP Code:
                    #region Using declarations
                    using System;
                    using System.Collections.Generic;
                    using System.ComponentModel;
                    using System.ComponentModel.DataAnnotations;
                    using System.Linq;
                    using System.Text;
                    using System.Threading.Tasks;
                    using System.Windows;
                    using System.Windows.Input;
                    using System.Windows.Media;
                    using System.Xml.Serialization;
                    using NinjaTrader.Cbi;
                    using NinjaTrader.Gui;
                    using NinjaTrader.Gui.Chart;
                    using NinjaTrader.Gui.SuperDom;
                    using NinjaTrader.Gui.Tools;
                    using NinjaTrader.Data;
                    using NinjaTrader.NinjaScript;
                    using NinjaTrader.Core.FloatingPoint;
                    using NinjaTrader.NinjaScript.DrawingTools;
                    
                    
                    
                    using System.Windows.Controls; // For TextBx
                    using System.Windows.Controls.Primitives; // For ButtonBase
                    
                    //using System.Windows.Forms;
                    //using System.Drawing;
                    //https://ninjatrader.com/support/forum/forum/historical-beta-archive/version-8-beta/81915-system-drawing-reference-missing?p=708541#post708541
                    using System.Drawing; // Cursor.Posi
                    //using System.Drawing.Primitives; // Cursor.Posi
                    
                    
                    using System.Windows.Interop;
                    using System.Runtime.InteropServices;
                    #endregion 
                    

                    State.DataLoaded and State.Terminated Button snippets
                    PHP Code:
                            else if (State == State.DataLoaded)
                            {
                              // Find our account
                              lock (Account.All)
                                myAccount = Account.All.FirstOrDefault(a => a.Name == AccountName);
                    
                              if (myAccount != null)
                                myAccount.OrderUpdate += Account_OrderUpdate;
                    
                              if (ChartControl != null)
                              {
                                ChartControl.PreviewKeyDown += ChartControl_PreviewKeyDown;
                    
                    
                                ChartControl.Dispatcher.InvokeAsync((Action)(() =>
                                {
                                  quantitySelector = (Window.GetWindow(ChartControl.Parent).FindFirst(" ChartTraderControlQuantitySelector") as NinjaTrader.Gui.Tools.QuantityUpDown);
                    
                                  // Grid already exists
                                  if (UserControlCollection.Contains(myGrid))
                                  return;
                    
                                  // Add a control grid which will host our custom buttons
                                  myGrid = new System.Windows.Controls.Grid
                                  {
                                  Name = "MyCustomGrid",
                                  // Align the control to the top right corner of the chart
                                  HorizontalAlignment = HorizontalAlignment.Right,
                                  VerticalAlignment = VerticalAlignment.Top,
                                  };
                    
                                  // Define the two columns in the grid, one for each button
                                  System.Windows.Controls.ColumnDefinition column1 = new System.Windows.Controls.ColumnDefinition();
                                  System.Windows.Controls.ColumnDefinition column2 = new System.Windows.Controls.ColumnDefinition();
                    
                                  // Add the columns to the Grid
                                  myGrid.ColumnDefinitions.Add(column1);
                                  myGrid.ColumnDefinitions.Add(column2);
                    
                                  // Define the custom Buy Button control object
                                  myBuyButton = new System.Windows.Controls.Button
                                  {
                                  Name = "MyBuyButton",
                                  Content = "LONG",
                                  Foreground = System.Windows.Media.Brushes.White,
                                  Background = System.Windows.Media.Brushes.Green
                                  };
                    
                                  // Define the custom Sell Button control object
                                  mySellButton = new System.Windows.Controls.Button
                                  {
                                  Name = "MySellButton",
                                  Content = "SHORT",
                                  Foreground = System.Windows.Media.Brushes.White,
                                  Background = System.Windows.Media.Brushes.Red
                                  };
                    
                                  // Subscribe to each buttons click event to execute the logic we defined in OnMyButtonClick()
                                  myBuyButton.Click += OnMyButtonClick;
                                  mySellButton.Click += OnMyButtonClick;
                    
                                  // Define where the buttons should appear in the grid
                                  System.Windows.Controls.Grid.SetColumn(myBuyButton , 0);
                                  System.Windows.Controls.Grid.SetColumn(mySellButto n, 1);
                    
                                  // Add the buttons as children to the custom grid
                                  myGrid.Children.Add(myBuyButton);
                                  myGrid.Children.Add(mySellButton);
                    
                    
                    
                    
                                  // Finally, add the completed grid to the custom NinjaTrader UserControlCollection
                                  UserControlCollection.Add(myGrid);
                    
                                }));      
                              }
                            }
                            else if (State == State.Terminated)
                            {
                              if (myAccount != null)
                                myAccount.OrderUpdate -= Account_OrderUpdate;
                    
                              if (ChartControl != null)
                              {
                                ChartControl.PreviewKeyDown -= ChartControl_PreviewKeyDown;    
                              }
                    
                    
                              if (myGrid != null)
                              {
                              if (myBuyButton != null)
                              {
                                myGrid.Children.Remove(myBuyButton);
                                myBuyButton.Click -= OnMyButtonClick;
                                myBuyButton = null;
                              }
                              if (mySellButton != null)
                              {
                                myGrid.Children.Remove(mySellButton);
                                mySellButton.Click -= OnMyButtonClick;
                                mySellButton = null;
                              }
                              }
                    
                              //Call a custom method to dispose of any leftover objects in State.Terminated
                              DisposeCleanUp();
                            } 
                    

                    Button Method Snippet
                    PHP Code:
                          // Define a custom event method to handle our custom task when the button is clicked
                          private void OnMyButtonClick(object sender, RoutedEventArgs rea)
                          {
                            System.Windows.Controls.Button button = sender as System.Windows.Controls.Button;
                            if (button != null)
                              Print(button.Name + " Clicked");
                          } 
                    

                    Button Press from PreviewKeyDown method Snippet
                    PHP Code:
                              protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
                              {
                                  // CLICK Button /Focus On Chart *Use Ctrl+Tab
                                  TriggerCustomEvent(m =>
                                  {
                                    if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
                                    {
                                      myBuyButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
                                    }
                                  }));
                              } 
                    

                    Comment


                      #11
                      I also tested setting the cursor to a position on the Chart / Screen
                      I want to simulate mouse movement every x seconds. For that, I'll use a timer (x seconds) and when the timer ticks I'll make the mouse movement. But, how can I make the mouse cursor move using C#?

                      without success
                      (the cursor does move to preset position when focused 1st on the Chart Panel,
                      but it doesn't when 1st focused in the Quantity Selector Box)

                      Using declarations assemblies
                      PHP Code:
                      #region Using declarations
                      using System;
                      using System.Collections.Generic;
                      using System.ComponentModel;
                      using System.ComponentModel.DataAnnotations;
                      using System.Linq;
                      using System.Text;
                      using System.Threading.Tasks;
                      using System.Windows;
                      using System.Windows.Input;
                      using System.Windows.Media;
                      using System.Xml.Serialization;
                      using NinjaTrader.Cbi;
                      using NinjaTrader.Gui;
                      using NinjaTrader.Gui.Chart;
                      using NinjaTrader.Gui.SuperDom;
                      using NinjaTrader.Gui.Tools;
                      using NinjaTrader.Data;
                      using NinjaTrader.NinjaScript;
                      using NinjaTrader.Core.FloatingPoint;
                      using NinjaTrader.NinjaScript.DrawingTools;
                      
                      
                      
                      using System.Windows.Controls; // For TextBx
                      using System.Windows.Controls.Primitives; // For ButtonBase
                      
                      //using System.Windows.Forms;
                      //using System.Drawing;
                      //https://ninjatrader.com/support/forum/forum/historical-beta-archive/version-8-beta/81915-system-drawing-reference-missing?p=708541#post708541
                      using System.Drawing; // Cursor.Posi
                      //using System.Drawing.Primitives; // Cursor.Posi
                      
                      
                      using System.Windows.Interop;
                      using System.Runtime.InteropServices;
                      #endregion 
                      

                      Mouse Event Controls declarations (at Class Level)
                      I have been trying to find a way to make a mouse click programmatically but the results I find are quit strainous based on my level. I know how to position the mouse and everything but the click. I...

                      PHP Code:
                      [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
                      public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
                      
                      private const int MOUSEEVENTF_LEFTDOWN = 0x02; // The left button is down.
                      private const int MOUSEEVENTF_LEFTUP = 0x04; // The left button is up.
                      
                      private const int MOUSEEVENTF_RIGHTDOWN = 0x08; // The right button is down.
                      private const int MOUSEEVENTF_RIGHTUP = 0x10; // The right button is up.
                      
                      private const int MOUSEEVENTF_ABSOLUTE = 0x8000; // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-mouse_event
                      
                      private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020; // The middle button is up.
                      private const int MOUSEEVENTF_MIDDLEUP = 0x0040; // The middle button is down.
                      
                      private const int MOUSEEVENTF_MOVE = 0x0001; // Movement occurred.
                      
                      private const int MOUSEEVENTF_XDOWN = 0x0080; //An X button was pressed.
                      private const int MOUSEEVENTF_XUP = 0x0100; // An X button was released.
                      
                      private const int MOUSEEVENTF_WHEEL = 0x0800; // The wheel button is rotated.
                      private const int MOUSEEVENTF_HWHEEL = 0x01000; // The wheel button is tilted. 
                      

                      SetCursorPos() boolean method declaration (at Class Level)
                      I have a two dimensional array with coordinates and i want to make the mouse move with the specific pattern those coordinates create in a WPF application. Can you help me? I've tried the Cursor cla...

                      PHP Code:
                      [DllImport("User32.dll")]
                      public static extern bool SetCursorPos(int xVal, int yVal); 
                      

                      Set Cursor and Trigger Mouse Clicks
                      I have been trying to find a way to make a mouse click programmatically but the results I find are quit strainous based on my level. I know how to position the mouse and everything but the click. I...

                      I'm setting up a simple C# application that sets window to foreground and performs clicks in a loop. (I wrote the same program on windows 7 few years ago. Everything performed well that time.) I am

                      What I want to do is to manipulate the mouse. It will be a simple macro for my own purposes. So it will move my mouse to certain position on the screen and click like I am clicking with certain int...

                      When I put this code Thread.Sleep(2000); it gives me the error: The name 'Thread' does not exist in the current context`. I already included the namespace using System.Threading;. See System.Thr...

                      PHP Code:
                                protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
                                {
                                    // SET CURSOR position
                                    TriggerCustomEvent(m =>
                                    {
                                      if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
                                      {
                                       SetCursorPos(100, 100);
                      
                                       //Call the imported function with the cursor's current position
                                       int X = Cursor.Position.X;
                                       int Y = Cursor.Position.Y;
                      
                                       Task.Delay(TimeSpan.FromSeconds(0.2)).Wait();
                                       mouse_event(MOUSEEVENTF_LEFTDOWN,100, 100, 0, 0);
                                       Task.Delay(TimeSpan.FromSeconds(0.2)).Wait();
                                       mouse_event(MOUSEEVENTF_LEFTUP, 100, 100, 0, 0);
                      
                                       Print("X : " + X + " Y : " + Y);
                                      }
                                    }));
                                }
                      
                      ======
                      or
                      https://ninjatrader.com/support/forum/forum/ninjatrader-8/indicator-development/1101107-get-x-y-position-of-current-window?p=1101137#post1101137
                      ======
                                protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
                                {
                                    // SET CURSOR position
                                    TriggerCustomEvent(m =>
                                    {
                                      if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
                                      {
                                        chartWindow = Window.GetWindow(this.ChartControl.Parent) as Chart;
                      
                                        SetCursorPos(Convert.ToInt32(chartWindow.Top), Convert.ToInt32(chartWindow.Left));
                      
                                       Task.Delay(TimeSpan.FromSeconds(0.2)).Wait();
                                       mouse_event(MOUSEEVENTF_LEFTDOWN, Convert.ToInt32(chartWindow.Top), Convert.ToInt32(chartWindow.Left), 0, 0);
                                       Task.Delay(TimeSpan.FromSeconds(0.2)).Wait();
                                       mouse_event(MOUSEEVENTF_LEFTUP, Convert.ToInt32(chartWindow.Top)-30, Convert.ToInt32(chartWindow.Left), 0, 0);
                      
                      
                                       Print("qX : " + (Convert.ToInt32(chartWindow.Top)) + " qY : " + (Convert.ToInt32(chartWindow.Left)));
                                      }
                                    }));
                                } 
                      

                      Or Mouse Mickey SetCursor Position and Triggers Mouse Clicks
                      Imported function declaration (at Class Level)
                      I have ListView with Images in my UserControl. When I am bringing the picture I have is redraw the picture when removing the mouse from the image picture nourish old. But when I am bringing a secon...

                      PHP Code:
                      
                              [DllImport("User32.dll",
                                    EntryPoint = "mouse_event",
                                    CallingConvention = CallingConvention.Winapi)]
                          internal static extern void Mouse_Event(int dwFlags,
                                                                  int dx,
                                                                  int dy,
                                                                  int dwData,
                                                                  int dwExtraInfo);
                      
                          [DllImport("User32.dll",
                                    EntryPoint = "GetSystemMetrics",
                                    CallingConvention = CallingConvention.Winapi)]
                          internal static extern int InternalGetSystemMetrics(int value); 
                      

                      Mouse Mickey SetCursor Position and Triggers Mouse Clicks
                      PHP Code:
                                        protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
                                        {
                                                // SET CURSOR position
                                                TriggerCustomEvent(m =>
                                                {
                                                    if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
                                                    {
                                                      int to_x = 500;
                                                      int to_y = 300;
                      
                                                      int screenWidth = InternalGetSystemMetrics(0);
                                                      int screenHeight = InternalGetSystemMetrics(1);
                      
                                                      // Mickey X coordinate
                                                      int mic_x = (int) System.Math.Round(to_x * 65536.0 / screenWidth);
                                                      // Mickey Y coordinate
                                                      int mic_y = (int) System.Math.Round(to_y * 65536.0 / screenHeight);
                      
                                                      // 0x0001 | 0x8000: Move + Absolute position
                                                      Mouse_Event(0x0001 | 0x8000, to_x, to_y, 0, 0);
                      //                           Task.Delay(TimeSpan.FromSeconds(0.2)).Wait();
                                                      // 0x0002: Left button down
                                                      Mouse_Event(0x0002, mic_x, mic_y, 0, 0);
                      //                           Task.Delay(TimeSpan.FromSeconds(0.2)).Wait();
                                                      // 0x0004: Left button up
                                                      Mouse_Event(0x0004, mic_x, mic_y, 0, 0);
                      
                                                      Print("X : " + to_x + " Y : " + to_y);
                      
                                                      Print("MX : " + mic_x + " MY : " + mic_y);
                                                    }
                                                }));
                                        } 
                      


                      System.Drawing.Point
                      I want to set mouse position at origin(0,0), we have tried using user32.dll and SetCursorPos() function its working fine. But we are getting some security error while importing user32.dll in our ru...


                      Using declarations
                      https://ninjatrader.com/support/foru...system-drawing
                      PHP Code:
                      #region Using declarations
                      using System;
                      using System.Collections.Generic;
                      using System.ComponentModel;
                      using System.ComponentModel.DataAnnotations;
                      using System.Linq;
                      using System.Text;
                      using System.Threading.Tasks;
                      using System.Windows;
                      using System.Windows.Input;
                      using System.Windows.Media;
                      using System.Xml.Serialization;
                      using NinjaTrader.Cbi;
                      using NinjaTrader.Gui;
                      using NinjaTrader.Gui.Chart;
                      using NinjaTrader.Gui.SuperDom;
                      using NinjaTrader.Gui.Tools;
                      using NinjaTrader.Data;
                      using NinjaTrader.NinjaScript;
                      using NinjaTrader.Core.FloatingPoint;
                      using NinjaTrader.NinjaScript.DrawingTools;
                      
                      
                      
                      using System.Windows.Controls; // For TextBx
                      using System.Windows.Controls.Primitives; // For ButtonBase
                      
                      //using System.Windows.Forms;
                      //using System.Drawing;
                      //https://ninjatrader.com/support/forum/forum/historical-beta-archive/version-8-beta/81915-system-drawing-reference-missing?p=708541#post708541
                      using System.Drawing; // Cursor.Posi
                      //using System.Drawing.Primitives; // Cursor.Posi
                      
                      
                      using System.Windows.Interop;
                      using System.Runtime.InteropServices;
                      #endregion 
                      

                      System.Drawing.Point PreviewkeyDown Method
                      PHP Code:
                                protected void ChartControl_PreviewKeyDown(object sender, KeyEventArgs e)
                                {
                                    // SET CURSOR position
                                    TriggerCustomEvent(m =>
                                    {
                                      if (Keyboard.IsKeyDown(Key.Insert) && (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
                                      {
                                       SetCursorPos(100, 100);
                                      System.Windows.Forms.Cursor.Position = new System.Drawing.Point(100, 100);
                                      }
                                    }));
                                } 
                      

                      Comment


                        #12
                        Bring Window to Front
                        https://stackoverflow.com/questions/...e-front-in-wpf


                        Also a possible VisualTree lead
                        https://ninjatrader.com/support/foru...rogramatically


                        I'll use the Ctrl+Tab solution for now, but I'd be curious to know if possible to get the focus on the window from inside of the Quantity Selector TextBox with a solution similar to .Activate() in WinForm if possible in Ninjatrader. Thanks!

                        Comment


                          #13
                          New Solution

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                          0 responses
                          666 views
                          0 likes
                          Last Post Geovanny Suaza  
                          Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                          0 responses
                          377 views
                          1 like
                          Last Post Geovanny Suaza  
                          Started by Mindset, 02-09-2026, 11:44 AM
                          0 responses
                          110 views
                          0 likes
                          Last Post Mindset
                          by Mindset
                           
                          Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                          0 responses
                          575 views
                          1 like
                          Last Post Geovanny Suaza  
                          Started by RFrosty, 01-28-2026, 06:49 PM
                          0 responses
                          580 views
                          1 like
                          Last Post RFrosty
                          by RFrosty
                           
                          Working...
                          X