Jump to content
IgImAx

[SOLVED] WinMenuSelectItem method cannot find in C#

Recommended Posts

IgImAx
Posted (edited)

Hi

 

UPDATED Notes: ===============================================================================

UPDATED: My main and second questions answered. Here the answers:

  1. To add/access WinMenuSelectItem you need to [Thanks to Fernando_Marinho]:
  • Add AutoItX.Dotnet in Manage NuGet Packages
  • Right Click in your Project -> Add -> Reference... -> COM ( Type Libraries )than, check the option AutoItX3 1.0 Type Library 
  • using AutoItX3Lib;
  • AutoItX3 au3 = new AutoItX3();
  • au3.WinMenuSelectItem("", ...)
  • My full source code in C# exists in 11 posts in below.
  1. How to access those overloaded methods in AutoitX3 that are not accessible via above method!? Or how to fix AutoitX3 DLL Registration need in target computers without Autoit pre-installed on them!? Please check my post at 14 posts below!

=============================================================================== Original Post:

 

 

I was writing a small app in Autoit to close µTorrent app. It was working. Then I try to import AutoItX into C#, but unfortunately this method

WinMenuSelectItem

Couldn't find by IntelliSense and If I typed completely it still give me this message:

Quote

'AutoitX' dose not contain a defination of 'WinMenuSelectItem'

Please check the image. I Google it and I found this QA at stackoverflow: Autoit error within C# application I saw they use this line:

au = new AutoItX3Lib.AutoItX3Class();

I figure it how to add 'AutoItX3Lib' to project (by adding 'AutoItX3.dll' to reference) but again! When I use this line:

var au = new AutoItX3Class();

I got this error message: Interop type 'AutoItX3Class' cannot be embedded. Use the applicable interface instead.

My system info:

Visual Studio 2017 Enterprise - v15.5.4

X64 Windows 10 Enterprise 1607

Thanks in advanced

IgImAx

Clipboard01.png

Edited by IgImAx
Added Updated Note

Teach Others to learn more yourself

My eBooks and Articles in Persian: IgImAx Home! * and more here

Share this post


Link to post
Share on other sites
Earthshine

Post code if you want help. There is a NuGet package for auto IT that works quite well


My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
IgImAx
Posted (edited)

 

 

Hi Earthshine

Thanks for your fast reply!

I already posted code! (But in the image! ;) ) Here it is my code in VS2017:

using System;
using AutoIt;

namespace Send_key_commant_to_a_Window
{
    class Program 
    {
        static void Main()
        {
            IntPtr intPtr = AutoItX.WinGetHandle("µtorrent");
            if (intPtr != IntPtr.Zero)
            {
                // This line wont compile! This is error message:
                //  'AutoitX' does not contain a definition of 'WinMenuSelectItem'
                AutoItX.WinMenuSelectItem(intPtr, "", "&File", "E&xit");
            }

        }
    }
}

And here is my AutoIt Code(this working without any problem):

$hWin = WinGetHandle("μTorrent")
$result = WinMenuSelectItem($hWin, "", "&File", "E&xit")
Quote

There is a NuGet package for auto IT that works quite well

Thanks, I check it, there were two Autoitx and Autoitx.DotNet the first one gives me this error:

PM> install-Package AutoItX


Attempting to gather dependency information for package 'AutoItX.3.3.12' with respect to project 'Send key commant to a Window', targeting '.NETFramework,Version=v4.5'
Gathering dependency information took 0.36 ms
Attempting to resolve dependencies for package 'AutoItX.3.3.12' with DependencyBehavior 'Lowest'
Resolving dependency information took 0 ms
Resolving actions to install package 'AutoItX.3.3.12'
Resolved actions to install package 'AutoItX.3.3.12'
Retrieving package 'AutoItX 3.3.12' from 'nuget.org'.
Adding package 'AutoItX.3.3.12' to folder 'D:\Worx\VC\Send key commant to a Window\packages'
Added package 'AutoItX.3.3.12' to folder 'D:\Worx\VC\Send key commant to a Window\packages'
Install failed. Rolling back...
Package 'AutoItX.3.3.12' does not exist in project 'Send key commant to a Window'
Removing package 'AutoItX.3.3.12' from folder 'D:\Worx\VC\Send key commant to a Window\packages'
Removed package 'AutoItX.3.3.12' from folder 'D:\Worx\VC\Send key commant to a Window\packages'
Executing nuget actions took 534.33 ms
install-Package : Failed to add reference to 'AutoItX3'.
  Could not load file or assembly 'AutoItX3.dll' or one of its dependencies. The module was expected to contain an assembly manifest.
At line:1 char:1
+ install-Package AutoItX
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
 
Time Elapsed: 00:00:02.6606769

But second one, installed without any problem. But still it cannot find 'WinMenuSelectItem' method!

Edited by IgImAx
add comment at C# sample code.

Teach Others to learn more yourself

My eBooks and Articles in Persian: IgImAx Home! * and more here

Share this post


Link to post
Share on other sites
Earthshine

Ok. I will take a look at it when I get back in the office tomorrow

  • Like 1

My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
Earthshine
Posted (edited)

yes, it says the same for me. that is not one of the methods. so, what exactly is it you want to do, just close uTorrent app? there is a ShutDown method

or you could just do this and not use autoit at all.

try
{
    foreach (Process proc in Process.GetProcessesByName("utorrent"))
            {
                proc.Kill();
            }
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

 

Edited by Earthshine

My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
IgImAx
Posted (edited)

Thanks Earthshine :)

 

Quote

yes, it says the same for me.

Well! This was my first intention! To make sure that I added Autoit library in the right way! :thumbsup: Thanks to you now I know that I did it right!

So now I would like to report it ['WinMenuSelectItem' method does not exists in AutoItX] so developers team put its fix in their To Do list.:ILA2:

I even try to copy all dll's manually fromlatest Autoit directory too! Still no hope!

 

 

Quote

so, what exactly is it you want to do, just close uTorrent app?

It's not the right way to close some apps by killing their process! They may have some unsaved data and sometimes they do not need that a user save them first, they will do it automatically when the user chooses the Exit option. In this case (µtorrent) if you kill its process, at next startup, it will start checking all files in its download list and it will make hug disk usage.

 

But still there are some other issues :mad2: that force me to use 'WinMenuSelectItem' method. I have to send some key commands to µTorrent window, while the workstation is in Lock mode. In that case and based on this article 'Why doesn't my script work on a locked workstation?' only these commands will work: 

ControlSend()  ControlSetText()  ControlClick()  WinWait()  WinExists()  WinMenuSelectItem()

That's why I need to use 'WinMenuSelectItem' method to send menu commands to µTorrent, not only to close it in the right way, but also to set other options in its menu too like this one:

$hWin = WinGetHandle("μTorrent")
$result = WinMenuSelectItem($hWin, "", "&Options", "&Auto Shutdown", "Shutdown when Downloads Complete")

 

At the end you may ask why you are not using AutoIt itself (To write the code and compile)!? I prefer C# and VS environment! Anyway. Thanks for your help and I hope this method add to AutoitX.DotNet library in near future updates or bug fixes.

 

Cheers :drinks:

 

Edited by IgImAx
some corrections

Teach Others to learn more yourself

My eBooks and Articles in Persian: IgImAx Home! * and more here

Share this post


Link to post
Share on other sites
Earthshine

lol, how about this

using System;
using AutoIt;

namespace Send_key_commant_to_a_Window
{
    class Program
    {
        static void Main()
        {
            IntPtr intPtr = AutoItX.WinGetHandle("µtorrent");
            if (intPtr != IntPtr.Zero)
            {
                // This line wont compile! This is error message:
                //  'AutoitX' does not contain a definition of 'WinMenuSelectItem'
                //AutoItX.WinMenuSelectItem(intPtr, "", "&File", "E&xit");
                AutoItX.ProcessClose("µtorrent");
            }
        }
    }
}

and if you prefer C#, then you don't need autoit at all anyway.


My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
IgImAx
Posted (edited)

ProcessClose() do the same thing that Process.kill do! Beside that I want to do other stuff I mention too!

Quote

and if you prefer C#, then you don't need autoit at all anyway.

lol don't get me wrong. I like to use AutoIt inside the VS not only the VS/C# to do automation. Autoit have many many many useful methods that if I want to write them with pure C# it's look like to inventing the bicycle again! And again!!! lol 

Edited by IgImAx

Teach Others to learn more yourself

My eBooks and Articles in Persian: IgImAx Home! * and more here

Share this post


Link to post
Share on other sites
Earthshine

then i suggest you use ControlSend and the like to automate the menu. it can probably be done.


My resources are limited. You must ask the right questions

 

Share this post


Link to post
Share on other sites
Fernando_Marinho

Hi IgImAx,

 

You need :

  • add AutoItX.Dotnet in Manage NuGet Packages ;
  • add  to your code :
    using AutoItX3Lib;
  • set instance, like :
AutoItX3 au3 = new AutoItX3();

than, call the method:

au3.WinMenuSelectItem("", ...)

 

Works for me ! :)

 

 

 

 

 

  • Like 1

Share this post


Link to post
Share on other sites
Fernando_Marinho
20 minutes ago, Fernando_Marinho said:

Hi IgImAx,

 

You need :

  • add AutoItX.Dotnet in Manage NuGet Packages ;
  • Right Click in your Project -> Add -> Reference... -> COM ( Type Libraries ) than, check the option AutoItX3 1.0 Type Library
  • image.png.2c136ee54f0ad85d945ac6f50001d450.png
  • add  to your code :
    using AutoItX3Lib;
  • set instance, like :
AutoItX3 au3 = new AutoItX3();

than, call the method:

au3.WinMenuSelectItem("", ...)

 

Works for me ! :)

 

 

 

 

 

 

  • Thanks 1

Share this post


Link to post
Share on other sites
IgImAx

Hi Fernando_Marinho

Quote

Right Click in your Project -> Add -> Reference... -> COM ( Type Libraries )than, check the option AutoItX3 1.0 Type Library

Thanks! That is working :lmao::thumbsup::guitar:

 

But now I found another problem! Please look at bellow Code:

using System;
using AutoIt;
using AutoItX3Lib;

namespace SendKeyCommand
{
    internal static class Program 
    {
        private static void Main()
        {
            var au = new AutoItX3();

            var intPtr = AutoItX.WinGetHandle("μTorrent");
            if (intPtr != IntPtr.Zero)
            {
                // intPtrString will be equal to intPtr in Hex
                var intPtrString = "0x" + intPtr.ToString("X8");
                // Bellow line, Doesn't Work!!? Why!?
                au.WinMenuSelectItem(intPtrString, "", "&Options", "&Auto Shutdown", "Shutdown when Downloads Complete");
                // Bellow line, Will work
                au.WinMenuSelectItem("μTorrent", "", "&Options", "&Auto Shutdown", "Shutdown when Downloads Complete");
            }
        }
    }
}

This line with a window handle as first parameter will not work: au.WinMenuSelectItem(intPtrString, ...

While the next line with a title will work!

I checked this line: var intPtr = AutoItX.WinGetHandle("μTorrent"); and it finds the right handle, and when I convert it to string  it is in the right format. (I checked to make sure it converts it to string in right way, for instance, if intPtr is 0x0008074a its string will be the same "0x0008074a"

 

So why is that line with window handle is not working!?

 


Teach Others to learn more yourself

My eBooks and Articles in Persian: IgImAx Home! * and more here

Share this post


Link to post
Share on other sites
BrewManNH

Why not just use the handle returned by WinGetHandle instead of converting it into a string and manipulating it to get it back to the format it was in previously?


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
IgImAx
10 minutes ago, BrewManNH said:

Why not just use the handle returned by WinGetHandle instead of converting it into a string and manipulating it to get it back to the format it was in previously?

It does not accept intPtr as first parameter, won't compile!  please check the image:

 

 

I found these two lines in AutoitX3_DLL.h file:
 

AU3_API int WINAPI AU3_WinMenuSelectItem(LPCWSTR szTitle, /*[in,defaultvalue("")]*/LPCWSTR szText, LPCWSTR szItem1, LPCWSTR szItem2, LPCWSTR szItem3, LPCWSTR szItem4, LPCWSTR szItem5, LPCWSTR szItem6, LPCWSTR szItem7, LPCWSTR szItem8);

AU3_API int WINAPI AU3_WinMenuSelectItemByHandle(HWND hWnd, LPCWSTR szItem1, LPCWSTR szItem2, LPCWSTR szItem3, LPCWSTR szItem4, LPCWSTR szItem5, LPCWSTR szItem6, LPCWSTR szItem7, LPCWSTR szItem8);

Is it possible to use/access WinMenuSelectItemByHandle method!?

intPtr.png


Teach Others to learn more yourself

My eBooks and Articles in Persian: IgImAx Home! * and more here

Share this post


Link to post
Share on other sites
IgImAx
Posted (edited)

Hi everyone :frantics:

First, I like to thank you all for all help and specially Fernando_Marinho for his solution.

I found my answer on this topic: C# use of the dll, some idears for you. about how to use those overloaded methods with "...ByHandle" postfix that doesn't exist in AutoitX3 lib in C#. (If we add it via COM to project reference)

using System;
using System.Runtime.InteropServices;
using AutoIt;

namespace SendKeyCommand
{
    internal static class Program 
    {
        [DllImport("AutoItX3.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int AU3_WinMenuSelectItemByHandle(IntPtr intPtr
            ,  string item1
            ,  string item2 = ""
            ,  string item3 = ""
            ,  string item4 = ""
            ,  string item5 = ""
            ,  string item6 = ""
            ,  string item7 = ""
            ,  string item8 = "");

        [DllImport("AutoItX3.dll", SetLastError = true, CharSet = CharSet.Auto)]
        private static extern int AU3_WinMenuSelectItem(string title
            ,  string text
            ,  string item1
            ,  string item2 = ""
            ,  string item3 = ""
            ,  string item4 = ""
            ,  string item5 = ""
            ,  string item6 = ""
            ,  string item7 = ""
            ,  string item8 = "");

        private static void Main()
        {
            var intPtr = AutoItX.WinGetHandle("μTorrent");
            if (intPtr != IntPtr.Zero)
            {
                AU3_WinMenuSelectItemByHandle(intPtr, "&File", "E&xit");
                // Or:
                // AU3_WinMenuSelectItem("μTorrent", "", "&File", "E&xit");
            }
        }
    }
}

Two important things:

  1. Omit all "[MarshalAs(UnmanagedType.LPStr)]" parts.
  2. No need to Register AutoItX3.DLL or AutoitX3_64.DLL files in the target computers. (Tested in VMware)
  3. No need to Reference AutoItX3 1.0 Type Library in C# (unless you do not want to use above method!) Just adds AutoItX.Dotnet in Manage NuGet Packages or Reference AutoItX3.Assembly.dll  manually from AutoitX folder under the audit installation folder.

Thanks again everyone.:drinks: Managers can kindly tag this topic as [ANSWERED] .

Edited by IgImAx
fix format

Teach Others to learn more yourself

My eBooks and Articles in Persian: IgImAx Home! * and more here

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • BigDaddyO
      By BigDaddyO
      I'm using WinMenuSelectItem() successfully in the application I'm automating but i'm looking for another feature.
      I use WinMenuSelectItem to Process a record.
      I then need to use WinMenuSelectItem to Save the record, but I shouldn't save before the Process step above finishes (Save option is always enabled).
      Sadly, the only way to know if Processing actually finished is when another menu item gets enabled (but I don't want to select that other menu item, just wait until it's enabled)
       
      The AU3Info tool doesn't show me anything for the menu bar items so I can't use ControlCommand IsEnabled.
       
      Anybody have other ideas?
       
      Quick example using SciTE menu bar as they act the same, AU3Info can't see those menu items either.
      ;Undo in SciTE, then wait until Redo is enabled but dont click it. If WinMenuSelectItem("[CLASS:SciTEWindow]", "", "&Edit", "&Undo") Then ConsoleWrite("Undo clicked" & @CRLF) ;How to I know if "&Edit", "&Redo" is enabled? Else ConsoleWrite("Can't find Undo" & @CRLF) EndIf ;Erase this line then run/F5 to get back  
       
      Thanks,
      Mike
    • PramodR
      By PramodR
       
      I see couple of ways to import module ,  one with specifying absolute path of the file to get imported, by this logic i believe to import a specific module will be like #include <c:\modulepath\duplicatemodule.au3>
      but i see some registry changes also made in this link , can someone explain why that registry change is really required.
       
    • PramodR
      By PramodR
       
      I am trying to execute a exe file in auto it as elevated previlage , but not successful till now . below are the methods i tried till now.
      Disabled UAC access from windows and  selected run only as administrator from executable properties.  i logged in as administrator but still exe needs to launch as run as administrator.
       
      Used Below methods from forum still no luck. anything i missing? i tried to use powershell.ps1 intead of exe as well.
      1.  Local $iPID = RunAs($sUserName, @ComputerName, $sPassword, $RUN_LOGON_NOPROFILE, "c:\Exec.exe", "", @SW_SHOWMAXIMIZED)
      2.  RunWait("C:\Automation\TestScripts\Writefilter.exe", @WindowsDir, @SW_MAXIMIZE)     - Std out error
       
      This command gives out put as running with admin rights
      #include <MsgBoxConstants.au3> #include <AutoItConstants.au3> #include <MsgBoxConstants.au3> #RequireAdmin Example() Func Example()     ; Change the username and password to the appropriate values for your system.     Local $sUserName = "Admin"     Local $sPassword = "PASSWORD"     Local $iPID = RunAs($sUserName, @ComputerName, $sPassword, 0, "noetpad.exe", "", @SW_SHOWMAXIMIZED)     ; Run Notepad with the window maximized. Notepad is run under the user previously specified. ;~     RunWait(@WindowsDir & "C:\automation\TestScripts\Writefilter.exe", @WindowsDir, @SW_MAXIMIZE) EndFunc   
    • PramodR
      By PramodR
      Hello,
      I have below code which execute well when all prerequisite met, when window pop up is not available its throwing an error. i want to capture error instead of error  out.
      error handling added in the code to capture it but it does not work still giving me error saying Variable must be of type "Object".
      $oCurWin.FindAll($treescope_subtree, $oCondition, $pElements)
      $oCurWin^ ERROR
      How to catch error properly . 
       
       
    • PramodR
      By PramodR
      Hello,
      I have to execute below block of code in elevated previllage, as that particular wmic class will work only with admin previlage.
      i am getting out put when i launch autoit as administrator,  but i will not be able to launch autoit as admin in this particular case but my user have admin rights.
      is there any better way i can run those command as administrator.?
      tried below steps:
      i have tried #RequireAdmin but that creates a user prompt  Tried using Runas command but gives error as wrong username or password , stuck with that step.  
       
×