I need to simulate input, why HtmlElement.Focus doesn't work?Why is Dictionary preferred over Hashtable in C#?Why is it important to override GetHashCode when Equals method is overridden?Calling GetGUIThreadInfo via P/InvokeWhy is setTimeout(fn, 0) sometimes useful?How can I connect to SAP from C# through the SAP NetWeaver RFC Library (sapnwrfc.dll)?How to kill an alert window in Windows using C#?How to send continuous keypress to a program?How do I get the value of text input field using JavaScript?Why not inherit from List<T>?System.ArgumentException thrown when switching tabs after creating new tab

Do I have to cite common CS algorithms?

80's/90's superhero cartoon with a man on fire and a man who made ice runways like Frozone

What does the phrase "pull off sick wheelies and flips" mean here?

What gave Harry Potter the idea of writing in Tom Riddle's diary?

TEMPO: play a sound in animated GIF/PDF/SVG

Do beef farmed pastures net remove carbon emissions?

Can "être sur" mean "to be about" ?

When were the tantalum capacitors first used in computing?

Safest way to store environment variable value in a file

On the Rømer experiments and the speed of light

Specific: effect of rm -r /./*

If clocks themselves are based on light signals, wouldn't we expect the measured speed of light to always be the same constant?

Are employers legally allowed to pay employees in goods and services equal to or greater than the minimum wage?

Word for an event that will likely never happen again

Loading military units into ships optimally, using backtracking

PhD advisor lost funding, need advice

how do companies get money from being listed publicly

How many people would you need to pull a whale over cobblestone streets?

Is there a standardised way to check fake news?

Submitting a new paper just after another was accepted by the same journal

The cat exchanges places with a drawing of the cat

Understanding this peak detector circuit

How can Radagast come across Gandalf and Thorin's company?

Why did I get only 5 points even though I won?



I need to simulate input, why HtmlElement.Focus doesn't work?


Why is Dictionary preferred over Hashtable in C#?Why is it important to override GetHashCode when Equals method is overridden?Calling GetGUIThreadInfo via P/InvokeWhy is setTimeout(fn, 0) sometimes useful?How can I connect to SAP from C# through the SAP NetWeaver RFC Library (sapnwrfc.dll)?How to kill an alert window in Windows using C#?How to send continuous keypress to a program?How do I get the value of text input field using JavaScript?Why not inherit from List<T>?System.ArgumentException thrown when switching tabs after creating new tab






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I'm trying to write a web bot which should be undetected so I don't use InnerText property and instead trying to simulate keypresses. To do so I need to focus an <input> element but the focus is switched to another textfield by itself instead even right after element.Focus() call.



I tried also using element.InvokeMember("click"); but it doesn't work either.



public partial class MainForm : Form

public MainForm()

InitializeComponent();


[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int uMsg, IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

public const Int32 WM_CHAR = 0x0102;
public const Int32 WM_KEYDOWN = 0x0100;
public const Int32 WM_KEYUP = 0x0101;
public const Int32 VK_RETURN = 0x0D;

IntPtr BrowserHandle

get

var hwnd = _browser.Handle;
hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell Embedding", null);
hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell DocObject View", null);
hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", null);
return hwnd;



readonly Random _rnd = new Random();

private void Form1_Load(object sender, EventArgs e)

_browser.Navigate("https://...");
_browser.DocumentCompleted += _browser_DocumentCompleted;


private async void _browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

if (e.Url.AbsoluteUri != "https://...") return;
var inputs = _browser.Document.GetElementsByTagName("input");

var el = inputs.OfType<HtmlElement>().FirstOrDefault(x => x.GetAttribute("className").Contains("login"));
await SendTextAsync(el, "sdfoj30jfoigjdlsgfdgd");



async Task SendTextAsync(HtmlElement element, string text)

for (var i = 0; i < text.Length; i++, await Task.Delay(_rnd.Next(0, 500)))

if (_browser.Document.ActiveElement != element)

element.Focus(); // doesn't work
if (_browser.Document.ActiveElement != element)

element.InvokeMember("click"); // either
if (_browser.Document.ActiveElement != element)

element.Focus();
await Task.Delay(_rnd.Next(50, 250)); // anyway




var c = text[i];
SendCharacter(c, BrowserHandle);



static void SendCharacter(char character, IntPtr hWnd)

var key = new IntPtr(character);
SendMessage(hWnd, WM_KEYDOWN, key, IntPtr.Zero);
SendMessage(hWnd, WM_CHAR, key, IntPtr.Zero);
SendMessage(hWnd, WM_KEYUP, key, IntPtr.Zero);




I expected this code to fill the login textfield but instead it writes a few characters there and others go to the password textfield.










share|improve this question
































    0















    I'm trying to write a web bot which should be undetected so I don't use InnerText property and instead trying to simulate keypresses. To do so I need to focus an <input> element but the focus is switched to another textfield by itself instead even right after element.Focus() call.



    I tried also using element.InvokeMember("click"); but it doesn't work either.



    public partial class MainForm : Form

    public MainForm()

    InitializeComponent();


    [DllImport("User32.dll")]
    public static extern int SendMessage(IntPtr hWnd, int uMsg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

    public const Int32 WM_CHAR = 0x0102;
    public const Int32 WM_KEYDOWN = 0x0100;
    public const Int32 WM_KEYUP = 0x0101;
    public const Int32 VK_RETURN = 0x0D;

    IntPtr BrowserHandle

    get

    var hwnd = _browser.Handle;
    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell Embedding", null);
    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell DocObject View", null);
    hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", null);
    return hwnd;



    readonly Random _rnd = new Random();

    private void Form1_Load(object sender, EventArgs e)

    _browser.Navigate("https://...");
    _browser.DocumentCompleted += _browser_DocumentCompleted;


    private async void _browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

    if (e.Url.AbsoluteUri != "https://...") return;
    var inputs = _browser.Document.GetElementsByTagName("input");

    var el = inputs.OfType<HtmlElement>().FirstOrDefault(x => x.GetAttribute("className").Contains("login"));
    await SendTextAsync(el, "sdfoj30jfoigjdlsgfdgd");



    async Task SendTextAsync(HtmlElement element, string text)

    for (var i = 0; i < text.Length; i++, await Task.Delay(_rnd.Next(0, 500)))

    if (_browser.Document.ActiveElement != element)

    element.Focus(); // doesn't work
    if (_browser.Document.ActiveElement != element)

    element.InvokeMember("click"); // either
    if (_browser.Document.ActiveElement != element)

    element.Focus();
    await Task.Delay(_rnd.Next(50, 250)); // anyway




    var c = text[i];
    SendCharacter(c, BrowserHandle);



    static void SendCharacter(char character, IntPtr hWnd)

    var key = new IntPtr(character);
    SendMessage(hWnd, WM_KEYDOWN, key, IntPtr.Zero);
    SendMessage(hWnd, WM_CHAR, key, IntPtr.Zero);
    SendMessage(hWnd, WM_KEYUP, key, IntPtr.Zero);




    I expected this code to fill the login textfield but instead it writes a few characters there and others go to the password textfield.










    share|improve this question




























      0












      0








      0








      I'm trying to write a web bot which should be undetected so I don't use InnerText property and instead trying to simulate keypresses. To do so I need to focus an <input> element but the focus is switched to another textfield by itself instead even right after element.Focus() call.



      I tried also using element.InvokeMember("click"); but it doesn't work either.



      public partial class MainForm : Form

      public MainForm()

      InitializeComponent();


      [DllImport("User32.dll")]
      public static extern int SendMessage(IntPtr hWnd, int uMsg, IntPtr wParam, IntPtr lParam);

      [DllImport("user32.dll", SetLastError = true)]
      static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

      public const Int32 WM_CHAR = 0x0102;
      public const Int32 WM_KEYDOWN = 0x0100;
      public const Int32 WM_KEYUP = 0x0101;
      public const Int32 VK_RETURN = 0x0D;

      IntPtr BrowserHandle

      get

      var hwnd = _browser.Handle;
      hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell Embedding", null);
      hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell DocObject View", null);
      hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", null);
      return hwnd;



      readonly Random _rnd = new Random();

      private void Form1_Load(object sender, EventArgs e)

      _browser.Navigate("https://...");
      _browser.DocumentCompleted += _browser_DocumentCompleted;


      private async void _browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

      if (e.Url.AbsoluteUri != "https://...") return;
      var inputs = _browser.Document.GetElementsByTagName("input");

      var el = inputs.OfType<HtmlElement>().FirstOrDefault(x => x.GetAttribute("className").Contains("login"));
      await SendTextAsync(el, "sdfoj30jfoigjdlsgfdgd");



      async Task SendTextAsync(HtmlElement element, string text)

      for (var i = 0; i < text.Length; i++, await Task.Delay(_rnd.Next(0, 500)))

      if (_browser.Document.ActiveElement != element)

      element.Focus(); // doesn't work
      if (_browser.Document.ActiveElement != element)

      element.InvokeMember("click"); // either
      if (_browser.Document.ActiveElement != element)

      element.Focus();
      await Task.Delay(_rnd.Next(50, 250)); // anyway




      var c = text[i];
      SendCharacter(c, BrowserHandle);



      static void SendCharacter(char character, IntPtr hWnd)

      var key = new IntPtr(character);
      SendMessage(hWnd, WM_KEYDOWN, key, IntPtr.Zero);
      SendMessage(hWnd, WM_CHAR, key, IntPtr.Zero);
      SendMessage(hWnd, WM_KEYUP, key, IntPtr.Zero);




      I expected this code to fill the login textfield but instead it writes a few characters there and others go to the password textfield.










      share|improve this question
















      I'm trying to write a web bot which should be undetected so I don't use InnerText property and instead trying to simulate keypresses. To do so I need to focus an <input> element but the focus is switched to another textfield by itself instead even right after element.Focus() call.



      I tried also using element.InvokeMember("click"); but it doesn't work either.



      public partial class MainForm : Form

      public MainForm()

      InitializeComponent();


      [DllImport("User32.dll")]
      public static extern int SendMessage(IntPtr hWnd, int uMsg, IntPtr wParam, IntPtr lParam);

      [DllImport("user32.dll", SetLastError = true)]
      static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

      public const Int32 WM_CHAR = 0x0102;
      public const Int32 WM_KEYDOWN = 0x0100;
      public const Int32 WM_KEYUP = 0x0101;
      public const Int32 VK_RETURN = 0x0D;

      IntPtr BrowserHandle

      get

      var hwnd = _browser.Handle;
      hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell Embedding", null);
      hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Shell DocObject View", null);
      hwnd = FindWindowEx(hwnd, IntPtr.Zero, "Internet Explorer_Server", null);
      return hwnd;



      readonly Random _rnd = new Random();

      private void Form1_Load(object sender, EventArgs e)

      _browser.Navigate("https://...");
      _browser.DocumentCompleted += _browser_DocumentCompleted;


      private async void _browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)

      if (e.Url.AbsoluteUri != "https://...") return;
      var inputs = _browser.Document.GetElementsByTagName("input");

      var el = inputs.OfType<HtmlElement>().FirstOrDefault(x => x.GetAttribute("className").Contains("login"));
      await SendTextAsync(el, "sdfoj30jfoigjdlsgfdgd");



      async Task SendTextAsync(HtmlElement element, string text)

      for (var i = 0; i < text.Length; i++, await Task.Delay(_rnd.Next(0, 500)))

      if (_browser.Document.ActiveElement != element)

      element.Focus(); // doesn't work
      if (_browser.Document.ActiveElement != element)

      element.InvokeMember("click"); // either
      if (_browser.Document.ActiveElement != element)

      element.Focus();
      await Task.Delay(_rnd.Next(50, 250)); // anyway




      var c = text[i];
      SendCharacter(c, BrowserHandle);



      static void SendCharacter(char character, IntPtr hWnd)

      var key = new IntPtr(character);
      SendMessage(hWnd, WM_KEYDOWN, key, IntPtr.Zero);
      SendMessage(hWnd, WM_CHAR, key, IntPtr.Zero);
      SendMessage(hWnd, WM_KEYUP, key, IntPtr.Zero);




      I expected this code to fill the login textfield but instead it writes a few characters there and others go to the password textfield.







      c# dom webbrowser-control bots






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 12:41







      Vlad

















      asked Mar 27 at 9:29









      VladVlad

      1,3621 gold badge13 silver badges31 bronze badges




      1,3621 gold badge13 silver badges31 bronze badges

























          1 Answer
          1






          active

          oldest

          votes


















          0














          The solution is to lookup for element with GetElementsByTagName each time instead of reusing the reference.






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55373785%2fi-need-to-simulate-input-why-htmlelement-focus-doesnt-work%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            The solution is to lookup for element with GetElementsByTagName each time instead of reusing the reference.






            share|improve this answer





























              0














              The solution is to lookup for element with GetElementsByTagName each time instead of reusing the reference.






              share|improve this answer



























                0












                0








                0







                The solution is to lookup for element with GetElementsByTagName each time instead of reusing the reference.






                share|improve this answer













                The solution is to lookup for element with GetElementsByTagName each time instead of reusing the reference.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 27 at 10:03









                VladVlad

                1,3621 gold badge13 silver badges31 bronze badges




                1,3621 gold badge13 silver badges31 bronze badges





















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55373785%2fi-need-to-simulate-input-why-htmlelement-focus-doesnt-work%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript