C#控制台打开VM虚拟机

添加引用->VixCOM.dll (在vix文件夹下)

VixWrapper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using VixCOM;

namespace VMHelper
{
    class VixWrapper
    {
        VixCOM.IVixLib vixLib = null;

        ulong m_vixError;
        VixCOM.IHost m_hostHandle = null;
        VixCOM.IVM m_vmHandle = null;

        public ulong GetError()
        {
            return m_vixError;
        }

        public  VixWrapper()
        {
            try
            {
                vixLib = new VixCOM.VixLibClass();
            }
            catch (COMException comExc)
            {
                System.Diagnostics.Trace.WriteLine(comExc.Message + "\n");
                throw;
            }
        }

        /// <summary>
        /// Creates a host handle
        /// </summary>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool Connect(string hostName, string userName, string password)
        {
            int hostType = string.IsNullOrEmpty(hostName) ? VixCOM.Constants.VIX_SERVICEPROVIDER_VMWARE_WORKSTATION : VixCOM.Constants.VIX_SERVICEPROVIDER_VMWARE_SERVER;

            int vixVersion = VixCOM.Constants.VIX_API_VERSION;

            vixVersion = -1;

            VixCOM.IJob jobHandle = vixLib.Connect(vixVersion, hostType, null, 0, userName, password, 0, null, null);

            int[] propertyIds = new int[1] { VixCOM.Constants.VIX_PROPERTY_JOB_RESULT_HANDLE };
            object results = new object();

            m_vixError = jobHandle.Wait(propertyIds, ref results);

            if (m_vixError == VixCOM.Constants.VIX_OK)
            {
                object[] objectArray = (object[])results;
                m_hostHandle = (VixCOM.IHost)objectArray[0];
                return true;
            }

            return false;
        }

        /// <summary>
        /// Opens the virtual machine specified in vmxFilePath
        /// </summary>
        /// <param name=”vmxFilePath”>The virtual machine vmx file to open</param>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool OpenVm(string vmxFilePath)
        {
            IJob jobHandle = m_hostHandle.OpenVM(vmxFilePath, null);

            int[] propertyIds = new int[1] { VixCOM.Constants.VIX_PROPERTY_JOB_RESULT_HANDLE };
            object results = new object();

            m_vixError = jobHandle.Wait(propertyIds, ref results);

            if (m_vixError == VixCOM.Constants.VIX_OK)
            {
                object[] objectArray = (object[])results;
                m_vmHandle = (VixCOM.IVM)objectArray[0];
                return true;
            }

            return false;
        }

        /// <summary>
        /// Power on the virtual machine
        /// </summary>
        /// <returns>true if succeeded, otherwise false</returns>  

        public bool PowerOn()
        {
            IJob jobHandle = m_vmHandle.PowerOn(VixCOM.Constants.VIX_VMPOWEROP_LAUNCH_GUI, null, null);
            m_vixError = jobHandle.WaitWithoutResults();

            if (m_vixError == VixCOM.Constants.VIX_OK)
            {
                jobHandle = m_vmHandle.WaitForToolsInGuest(300, null);

                m_vixError = jobHandle.WaitWithoutResults();
            }

            return (m_vixError == VixCOM.Constants.VIX_OK);
        }

        /// <summary>
        /// Starts a snapshot of a virtual machine
        /// </summary>
        /// <param name=”snapshot_name”>The name of the snapshot to start</param>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool RevertToLastSnapshot()
        {
            ISnapshot snapshot = null;
            m_vixError = m_vmHandle.GetRootSnapshot(0, out snapshot);

            if (m_vixError == VixCOM.Constants.VIX_OK)
            {
                IJob jobHandle = m_vmHandle.RevertToSnapshot(snapshot, 0, null, null);

                m_vixError = jobHandle.WaitWithoutResults();
            }

            return (m_vixError == VixCOM.Constants.VIX_OK);
        }

        /// <summary>
        /// Login to the virtual machine
        /// </summary>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool LogIn(string username, string password)
        {
            IJob jobHandle = m_vmHandle.LoginInGuest(username, password, 0, null);
            m_vixError = jobHandle.WaitWithoutResults();

            return (m_vixError == VixCOM.Constants.VIX_OK);
        }

        /// <summary>
        /// Creates the directory in the Virtual Machine
        /// </summary>
        /// <param name=”pathName”></param>
        /// <returns></returns>
        public bool CreateDirectoryInVm(string pathName)
        {
            IJob jobHandle = m_vmHandle.CreateDirectoryInGuest(pathName, null, null);
            m_vixError = jobHandle.WaitWithoutResults();

            return (m_vixError == VixCOM.Constants.VIX_OK);
        }

        /// <summary>
        /// Copies a file from the host machine to the virtual machine
        /// </summary>
        /// <param name=”sourceFile”>The source file on the host machine</param>
        /// <param name=”destinationFile”>The destination on the VM</param>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool CopyFileToVm(string sourceFile, string destinationFile)
        {
            //
            // Copy files from host to guest
            //
            IJob jobHandle = m_vmHandle.CopyFileFromHostToGuest(sourceFile, destinationFile,
                0, null, null);
            m_vixError = jobHandle.WaitWithoutResults();

            return (m_vixError == VixCOM.Constants.VIX_OK);
        }

        /// <summary>
        /// Copies a file from the virtual machine to the host machine
        /// </summary>
        /// <param name=”sourceFile”>The source file on the virtual machine</param>
        /// <param name=”destinationFile”>The destination on the host machine</param>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool CopyFileFromVm(string sourceFile, string destinationFile)
        {
            //
            // Copy files from host to guest
            //
            IJob jobHandle = m_vmHandle.CopyFileFromGuestToHost(sourceFile, destinationFile,
                0, null, null);
            m_vixError = jobHandle.WaitWithoutResults();

            return (m_vixError == VixCOM.Constants.VIX_OK);
        }

        /// <summary>
        /// Runs a program on the virtual machine
        /// </summary>
        /// <param name=”exePath”>The path of the program on the virtual machine</param>
        /// <param name=”parameters”>The parameters to pass to the executable</param>
        /// <param name=”resultCode”>The result code returned from the program that ran on the VM</param>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool RunProgram(string exePath, string parameters, out int resultCode)
        {
            resultCode = -1;

            IJob jobHandle = m_vmHandle.RunProgramInGuest(exePath,
                parameters, VixCOM.Constants.VIX_RUNPROGRAM_ACTIVATE_WINDOW, null, null); // clientData  

            int[] propertyIds = new int[1] { VixCOM.Constants.VIX_PROPERTY_JOB_RESULT_GUEST_PROGRAM_EXIT_CODE };
            object results = new object();
            m_vixError = jobHandle.Wait(propertyIds, ref results);

            if (m_vixError == VixCOM.Constants.VIX_OK)
            {
                object[] objectArray = (object[])results;
                resultCode = (int)objectArray[0];
                return true;
            }

            return false;
        }

        /// <summary>
        /// Power off the virtual machine
        /// </summary>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool PowerOff()
        {
            IJob jobHandle = m_vmHandle.PowerOff(VixCOM.Constants.VIX_VMPOWEROP_NORMAL, null);
            m_vixError = jobHandle.WaitWithoutResults();

            return (m_vixError == VixCOM.Constants.VIX_OK);
        }
        /// <summary>
        /// Restart the virtual machine
        /// </summary>
        /// <returns>true if succeeded, otherwise false</returns>
        public bool Restart()
        {
            IJob jobHandle = m_vmHandle.Reset(VixCOM.Constants.VIX_VMPOWEROP_NORMAL, null);
            m_vixError = jobHandle.WaitWithoutResults();

            return (m_vixError == VixCOM.Constants.VIX_OK);

        }  

    }
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using VMHelper;

namespace VixWrapperTest
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //VixWrapper.VixWrapper vix = new VixWrapper.VixWrapper();
                VixWrapper wrapper = new VixWrapper();

                wrapper.Connect(null, "Administrator", null);

                wrapper.OpenVm(@"E:\win xp\Windows XP Professional.vmx");//安装好的虚拟机.vmx的实际路径

                wrapper.PowerOn();

                wrapper.PowerOff();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

    }
}

本程序实现了通过VS控制台打开vm虚拟机的功能,有兴趣的可以去调用剩下的函数,做个时延函数,然后完成其他任务。

由于网上关于VIX_API的调用的实例非常少,后面想通过WF来做几个btn实现简单便捷的开关机,调用虚拟机里的程序来完成工作等功能,出现了接口对象赋值未初始化的问题,有兴趣的可以联系下我,共同研究。

时间: 2024-11-28 19:43:18

C#控制台打开VM虚拟机的相关文章

VM虚拟机无法拖拽、粘贴、复制

VM无法从客户机拖放/复制文件到虚拟机的解决办法: 将这两项取消勾选,点击[确定].再次打开,勾选,点击[确定] 原因分析:可能是VM中默认是不支持该功能的,但是在配置窗体上确实默认打钩打上的. 依据:在操作过程中,你可以查看该虚拟机的的配置文件(*.vmx).观察以下节点 isolation.tools.copy.disable = "FALSE" isolation.tools.dnd.disable = "FALSE" isolation.tools.past

XEN创建出VM虚拟机文件物理路径

XEN创建出VM虚拟机文件物理路径. 打开下面这个文件,找到# Directory tree containing VM metadata行. vi /etc/xenopsd.conf 默认路径是 /var/run/nonpersistent/xenopsd 在VM夹里以UUID命名的文件夹.UUID在对应的XEN center里--虚拟机--常规选项卡里可以看到.

[Windows]Win10下VM虚拟机桥接模式无法上网的解决办法

Win10出来了,赶紧尝尝鲜.既然是预览版,肯定会出现以前没有过的问题.这不,问题马上就来了.我的VM虚拟机本来在Win8.1下使用桥接模式是可以上网的,但是现在不可以了.重置了好几次虚拟网络,NAT可以,桥接不行.怎么办呢?上网搜也没有人能解决.我自己就瞎鼓捣,没想到竟然给解决了! Win10的适配器中有一项“桥接”功能,不知道此“桥接”是不是彼“桥接”呢?死马当活马医吧!(其实这种方法和微软Hyper-V虚拟机网络访问机制很像,而且微软Hyper-V和VM不能共存,可能双方都在寻找合适的解决

VM虚拟机安装64位CentOS无法安装的问题

问题描述: VM虚拟机安装64位CentOS时提示 解决办法: 1)到网上下载一个securable.exe,测试以下机器是否支持VT. locked on:代表已经开启了VT了. locked off:可能是你bios中没有打开vt开关,或是cpu不支持. no:没有VT功能. 2)我最初的状态为:locked off,于是重启机器,进入bios(开机时按delete键即可进入bios界面),特别注意了,这里要修改1个地方: CPU的虚拟化开关:CPU选项里面有一个Inter Virtual

VM虚拟机下在LINUX上安装ORACLE 11G单实例数据库

VM虚拟机下在LINUX上安装ORACLE 11G单实例数据库 1.环境及安装前规划:虚拟机及OS如下 环境:VMware Wordstation ACE版 6.0.2 操作系统:OracleLinux-R5-U8-Server-i386-dvd    3.2G 安装操作系统,这里需要注意的是磁盘空间要预留足够. 我的规划是: 虚拟机分配1024M内存,当然如果主机内存足够,安装时内存设置2048M可以更快. 虚拟机分配一块磁盘,30G磁盘空间. /boot 100M ext3 /    20G

Linux 入门 1 (vm虚拟机安装openSUSE 11,SecureCRT远程连接)

Linux版本: openSUSE-11.0-GNOME-LiveCD-i386.torrent ,(680M)下载地址:http://ftp5.gwdg.de/pub/opensuse/discontinued/distribution/11.0/iso/torrent/ 安装都是默认的,设的硬盘大小是8G,内存1G,网络连接时桥接,分区挂载都是快速安装默认的,自己没修改. 安装好后,ifconfig查看suse的ip为192.168.1.103,而物理机(笔记本)是192.168.1.100

VM虚拟机不能上网的问题解决

VM虚拟机不能上网的问题解决 说在前面的话:很多网友看了我的文章后,虚拟机还是不能上网,就联系我帮忙,结果帮他们给弄好后,都说怪自己太粗心,没有仔细看文章.我不是怕网友麻烦我,我是真诚的希望各位要首先认真仔细地看完文章,一步一步按照文章操作,一般自己都可以解决问题 .确实不行的,欢迎联系我! 关于VM虚拟机上网的问题,有很多网友求助我,说虚拟机不能上网.今天我们就来探讨一下VM虚拟机不能上网的问题. 首先明确一点:VM虚拟机上网是不用拨号的,直接上网(除非你不想虚拟机和主机同时上网). VM软件

VM虚拟机安装OS系统以及VM TOOL的安装总结

新建虚拟机 选择CDR后缀系统或者ISO后缀都可以 选择对应版本 启动虚拟机会报错 必须先打开安装地址  找到 "自己命名的机器名".vmx  用 text打开 在 smc.present = "TRUE"  后面加smc.version = "0" 保存即可 必须先在实用工具先分区 然后才会出现安装的磁盘. 系统安装完毕后,无法从物理机和虚拟机直接移动和复制文件 这个时候右键点击虚拟机设置 点击浏览 找到安装VM虚拟机的路径 在里面找到darw

Linux centOS的vm虚拟机配置详细 中文版

这里以安装cenOS6.6 为例 如果想要需要cenos 6.6 ios文件的朋友看我的另一篇关于cenos6.6版本的下载详细 文中内容是摘抄自老男孩老师的<linux 跟老男孩学Linux运维>  文中资料所有版权属于老男孩老师 我只是实践分析实践经验 如需查看查看英文版 请购买书籍或者查看老男孩或者赵班长的博客 为什么要做这个博客 老男孩老师的推荐是是英语状态下安装 我觉得这很有必要 做这篇博文是给误选中文安装的朋友一个参考,也是给我自己提供总结的机会 准备 cenos 6.6 x86