Jump to content

[SOLVED] WinMenuSelectItem method cannot find in C#


Recommended Posts

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

Link to post
Share on other sites

 

 

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

Link to post
Share on other sites

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

 

Link to post
Share on other sites

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

Link to post
Share on other sites

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

 

Link to post
Share on other sites

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

Link to post
Share on other sites
  • 2 weeks later...
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 ! :)

 

 

 

 

 

 

Link to post
Share on other sites

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

Link to post
Share on other sites

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

Link to post
Share on other sites
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

Link to post
Share on other sites

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

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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By argumentum
      ...trying to get the MonthCal font size, given that when loading it ( GUICtrlCreateMonthCal() ), this Win32 control has the font size auto-adjusted by the OS and working with display scaling, getting the font that is visually congruent, getting this value should make it the perfect font size for my GUI.
      My question is how to get this ( https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.monthcalendar.size?view=windowsdesktop-6.0 ) working from within AutoIt3.
      This should work in any PC given that the .NET supports this call in every version of .NET
      Thanks. ( I have no clue of C# or .NET )
    • By Skeletor
      Hi All,
      So I was searching through the internet and found a plethora of information to learn C#. 
      However, some are way below par and does not explain very well. 

      So, anyone can suggest a proper website or eBook or video course explaining C#?
       
      I've learnt AutoIt (still I'm learning it) by making small programs, reading the forums, going through the F1 guide (huge help, seriously this helps alot) and reading the Wiki.
      Any direction would be appreciated, just not off the edge of a cliff.. 
    • By HoratioCaine
      Hi, everyone.
      I have python code for kill window,  but sometimes it does not working .

      My code is :
      import subprocess import time import ctypes au3_dll = ctypes.windll.LoadLibrary(r'D:\AutoIt\AutoItX3.dll') def close_ie(title): subprocess.Popen(f"C:/Program Files (x86)/Internet Explorer/iexplore.exe https://cn.bing.com/?mkt=zh-CN") time.sleep(2) au3_dll.AU3_Opt("WinTitleMatchMode", 2) ret = au3_dll.AU3_WinKill(title, "") print(ret) if __name__ == '__main__': title = '必应 - Internet Explorer' for i in range(10): close_ie(title) My expectation is that all IE windows will be closed, but there will always be a few windows still there.
      My env: win10 64bit python3.6.4 autoit v3.3.14.2  
      Any suggestions would be appreciated 
    • By Colduction
      Hi AutoIt programmers, excuse me for bothering you with multiple topics.

      In AutoIt we can use Number() function to convert Hex string to number but it's output is different of C# output & and i wanna make it's output like AutoIt code.

      For e.g I use this in AutoIt:
      Local $dBinary = Binary("Hello") ; Create binary data from a string. Local $dExtract = Number(BinaryMid($dBinary, 1, 5)) ConsoleWrite($dExtract & @CRLF) And i use this for C#:
      using System; using System.Text; //NameSpace Is Use of Project Name namespace TEST { class Program { public static void Main(string[] args) { //declaring a variable and assigning hex value string dd = ToHex("Hello", Encoding.ASCII); decimal d = Int64.Parse(dd, System.Globalization.NumberStyles.HexNumber); Console.WriteLine("Result: " + d); //hit ENTER to exit Console.ReadLine(); } public static string ToHex(string sInput, Encoding oEncoding, bool b0x_Prefix = false) { byte[] a_binaryOutput = oEncoding.GetBytes(sInput); string sOutput = BitConverter.ToString(a_binaryOutput).Replace("-", ""); if (b0x_Prefix == false) { return sOutput; } else { return "0x" + sOutput; } } } }
      I say once again that excuse me for creating new topic, in fact i'm making a library for GAuthOTP from a topic in AutoIt.
    • By learner123
      Hi All,
       
      I am new to this AUTO IT and I have created a script that will open an app,enter pin and copy the code generated to clipboard. My java code call this autoIT script and use the copied generated code from clipboard.
      This works fine when server  window is on focus. My server is an windows server. 
      But when I minimize or disconnect the server, the script opens the app.exe but doesn't copy any value to clipboard.  
      Can anyone help me on this 😐
       
      Run("C:\Program Files (x86)\RSA SecurID Software Token\SecurID.exe")
      Local $hWnd=WinWait("abc - RSA SecurID Token") ; waits until the window is the active window
      $hWin = WinGetHandle("abc - RSA SecurID Token");
      ControlSend($hWnd,"","","1111") ; simulates pressing the Home key
      ControlSend($hWnd,"","","{ENTER}");
      ControlSend($hWnd,"","","^c");
      Sleep(1000) ;
      ControlSend($hWnd,"","","^c");
       
×
×
  • Create New...