Word中互操作的自动化FilePrintSetup错误

Word中互操作的自动化FilePrintSetup错误

本文介绍了Microsoft Word中互操作的自动化FilePrintSetup错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到有一个打印机错误。绑发送使用自动化打印作业到打印机在Windows 7上使用Word 2010中相同的代码工作正常的Windows XP框Word 2007年的时候,我不知道如果Windows 7或Word 2010中导致错误。



任何帮助表示赞赏。

 使用的Microsoft.Office.Interop.Word; 
.....

对象oWordbasic = wordDoc.Application.WordBasic;

对象[] = argValues新的对象[] {值,1}; //第一个参数是一个打印机名称
的String [] = argNames新的String [] {打印机,并将DoNotSetAsSysDefault};

//错误这里
oWordbasic.GetType()InvokeMember(FilePrintSetup,System.Reflection.BindingFlags.InvokeMethod,空,oWordbasic,argValues,NULL,NULL,argNames)。



我得到下面的错误

  System.Reflection.TargetInvocationException被抓住
消息=异常已被调用的目标引发异常。
来源= mscorlib程序
堆栈跟踪:
在System.RuntimeType.InvokeDispMethod(字符串名称,的BindingFlags invokeAttr,对象目标,对象[] ARGS,布尔[] byrefModifiers,文化的Int32,字符串[] namedParameters )在System.RuntimeType.InvokeMember(字符串名称,的BindingFlags的BindingFlags,粘结剂粘合,对象,目标
,对象[] providedArgs,ParameterModifier []修饰符,CultureInfo的文化的String [] namedParams)
在PBP.ABC .Framework.Wrappers.Microsoft.Word.WordDocument.set_ActivePrinterName(字符串值)
的InnerException信息:System.Runtime.InteropServices.COMException
HELPLINK = wdmain11.chm#24696
消息=有一个打印机错误。
源= Microsoft Word中
错误码= -2146827168
的InnerException:

如果我离开了打印机参数,调用的工作,但不能打印到指定的打印机。它会打印到默认打印机。



感谢。


解决方案

可能为你工作 - 这是我在Word中做到不改变活动打印机,我得到了一个错误,打印,发现有时候字很喜欢刚刚打印机名称和其他时间想也有口。

...来获取打印机名称和端口使用InstalledPrinter如下

 私人InstalledPrinter PreferredPrinter {搞定;组; } 
私人InstalledPrinter DefaultPrinter {搞定;组; }

私人无效SetDefaultAndPreferredPrinters()
{
如果(UserSettings [SETTING_PREFERRED_PRINTER] == NULL)
{
UserSettings [SETTING_PREFERRED_PRINTER] =的String.Empty ;
}
_preferredPrinterName =((串)UserSettings [SETTING_PREFERRED_PRINTER])修剪()。

名单,LT; InstalledPrinter> installedPrinters = InstalledPrinter.GetList();

DefaultPrinter = NULL;
PreferredPrinter = NULL;

的foreach(InstalledPrinter installedPrinter在installedPrinters)
{
如果(installedPrinter.IsDefault)
{
DefaultPrinter = installedPrinter;
}
如果(installedPrinter.Name.Equals(_preferredPrinterName,StringComparison.InvariantCultureIgnoreCase))
{
PreferredPrinter = installedPrinter;
}
}
}

公共枚举PrinterStatus {
其它= 1,
未知,
空闲,
打印,
热身,
停止,
离线,
降级
}

公共类InstalledPrinter {

私人静态只读的ILog _s_logger =
LogManager.GetLogger(MethodBase.GetCurrentMethod()DeclaringType);

公共字符串的DriverName {搞定;组; }

公共字符串位置{搞定;组; }

公共字符串名称{;组; }

公共BOOL网{搞定;组; }

公共字符串端口名称{搞定;组; }

公共字符串服务器名{获得;组; }

公共BOOL共享{搞定;组; }

公共PrinterStatus状态{搞定;组; }

公共BOOL WorkOffline {搞定;组; }

公共BOOL ISDEFAULT {搞定;组; }

公共静态列表< InstalledPrinter>的GetList()
{
PrinterSettings PS =新PrinterSettings();
串sDefault = ps.PrinterName;

查询字符串=SELECT * FROM Win32_Printer

ManagementObjectSearcher搜索=新ManagementObjectSearcher(查询);

ManagementObjectCollection结果= searcher.Get();

名单,LT; InstalledPrinter>名单=新名单,LT; InstalledPrinter>(results.Count);

的foreach(的ManagementObject printManagementObject在结果)
{
InstalledPrinter进入=新InstalledPrinter();

的foreach(的PropertyInfo的PropertyInfo在typeof运算(InstalledPrinter).GetProperties()){
[对象] oparams = {1};
如果(propertyInfo.Name!=ISDEFAULT){//该ISDEFAULT属性在逻辑上制定出来的,物业的其余部分相同映射到WMI查询结果的列。
尝试{
oparams [0] = ConvertValue(
printManagementObject [propertyInfo.Name],propertyInfo.PropertyType);
propertyInfo.GetSetMethod()调用(
项,
oparams)。
}赶上(例外五){
_s_logger.Error(的String.Format(无法枚举打印机属性名称:{0}类型:{1},propertyInfo.Name,propertyInfo.PropertyType) );
}
}
}
_s_logger.Info(的String.Format(说完列举打印机的属性:{0}?,entry.Name == NULL<&空GT ;:entry.Name));
如果(sDefault.Equals(entry.Name,StringComparison.CurrentCultureIgnoreCase)){
entry.IsDefault = TRUE;
}
list.Add(输入);
}
返回列表;
}

私有静态对象ConvertValue(对象的值,类型型)
{
如果(值!= NULL)
{
对象printerStatusRetval = NULL;
如果(类型== typeof运算(DATETIME))
{
串时间= value.ToString();
时间= time.Substring(0,time.IndexOf()。);
返回DateTime.ParseExact(时间,YYYYMMDDHHMMSS,NULL);
}
,否则如果(类型== typeof运算(长))
返回Convert.ToInt64(值);
,否则如果(类型== typeof运算(INT))
返回Convert.ToInt32(值);
,否则如果(类型== typeof运算(短))
返回Convert.ToInt16(值);
,否则如果(类型== typeof运算(字符串))
返回value.ToString();
,否则如果(类型== typeof运算(PrinterStatus))
尝试{
printerStatusRetval = Enum.Parse(typeof运算(PrinterStatus),value.ToString());
}赶上(例外五){
_s_logger.Error(的String.Format(无法PrinterStatus转换与价值{0},值));
printerStatusRetval = value.ToString();
}
返回printerStatusRetval;
}
返回NULL;
}



}



...然后实例化字之后我有这样的事情来设置打印机:

  [对象] oWordDialogParams = {PreferredPrinter.Name ,真实}; 
[对象] oWordDialogParamsWithPort = {的String.Format({0}在{1},PreferredPrinter.Name,PreferredPrinter.PortName),真};
的String [] = argNames {打印机,并将DoNotSetAsSysDefault};
// oWord是我自己的类,提供各地的MS Word $ B $一个相当简单的包装b oWord.Application.ActivePrinter = UserSettings [SETTING_PREFERRED_PRINTER]作为字符串;
对话框PrintDialog类= oWord.Application.Dialogs [WdWordDialog.wdDialogFilePrintSetup]
对象的WordBasic = oWord.Application.WordBasic;
尝试{
wordBasic.GetType()。InvokeMember(FilePrintSetup
,BindingFlags.InvokeMethod
,空
,的WordBasic
,oWordDialogParams
,空
,空
,argNames);
}赶上(例外五){
_s_logger.Info(无法使用打印机名称打印,打印机试图名称和端口,E);
尝试{
wordBasic.GetType()。InvokeMember(FilePrintSetup
,BindingFlags.InvokeMethod
,空
,的WordBasic
,oWordDialogParamsWithPort
,空
,空
,argNames);
}赶上(例外E2){
_s_logger.Info(无法使用打印机名称和端口打印,E2);
抛出;
}
}


I am getting "There is a printer error." when tying to send a print job to a printer using automation on Windows 7 with Word 2010. Same code works fine on Windows XP box with Word 2007. I am not sure if Windows 7 or word 2010 is causing the error.

Any help appreciated

using Microsoft.Office.Interop.Word;
.....

object oWordbasic = wordDoc.Application.WordBasic;

object[] argValues = new object[] { value, 1  }; //first arg is a printer name
String[] argNames = new String[] { "Printer", "DoNotSetAsSysDefault", };

//Error Here
oWordbasic.GetType().InvokeMember("FilePrintSetup", System.Reflection.BindingFlags.InvokeMethod, null, oWordbasic, argValues, null, null, argNames);

I get the Error Below

System.Reflection.TargetInvocationException was caught
  Message=Exception has been thrown by the target of an invocation.
  Source=mscorlib
  StackTrace:
       at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
       at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
       at PBP.ABC.Framework.Wrappers.Microsoft.Word.WordDocument.set_ActivePrinterName(String value) in
  InnerException: System.Runtime.InteropServices.COMException
       HelpLink=wdmain11.chm#24696
       Message=There is a printer error.
       Source=Microsoft Word
       ErrorCode=-2146827168
       InnerException:

If I leave out the printer parameters, the invoke work but not printing to the printer specified. It will print to the default printer.

Thanks.

解决方案

Might work for you - this is what I had to do in Word to print without changing the active printer, I was getting an error and found that sometimes Word liked just the printer name and other times wanted to also have the port.

... to get the printer names and ports use InstalledPrinter as below

private InstalledPrinter PreferredPrinter { get; set; }
private InstalledPrinter DefaultPrinter { get; set; }

    private void SetDefaultAndPreferredPrinters()
    {
        if (UserSettings[SETTING_PREFERRED_PRINTER] == null)
        {
            UserSettings[SETTING_PREFERRED_PRINTER] = string.Empty;
        }
        _preferredPrinterName = ((string)UserSettings[SETTING_PREFERRED_PRINTER]).Trim();

        List<InstalledPrinter> installedPrinters = InstalledPrinter.GetList();

        DefaultPrinter = null;
        PreferredPrinter = null;

        foreach (InstalledPrinter installedPrinter in installedPrinters)
        {
            if (installedPrinter.IsDefault)
            {
                DefaultPrinter = installedPrinter;
            }
            if (installedPrinter.Name.Equals(_preferredPrinterName, StringComparison.InvariantCultureIgnoreCase))
            {
                PreferredPrinter = installedPrinter;
            }
        }
    }

public enum PrinterStatus{
  Other = 1,
  Unknown,
  Idle,
  Printing,
  Warmup,
  Stopped,
  Offline,
  Degraded
}

public class InstalledPrinter{

        private static readonly ILog _s_logger =
        LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

public string DriverName { get; set; }

public string Location { get; set; }

public string Name { get; set; }

public bool Network { get; set; }

public string PortName { get; set; }

public string ServerName { get; set; }

public bool Shared { get; set; }

public PrinterStatus Status { get; set; }

public bool WorkOffline { get; set; }

public bool IsDefault { get; set; }

public static List<InstalledPrinter> GetList()
{
    PrinterSettings ps = new PrinterSettings();
        string sDefault = ps.PrinterName;

    string query = "Select * From Win32_Printer";

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

    ManagementObjectCollection results = searcher.Get();

    List<InstalledPrinter> list = new List<InstalledPrinter>(results.Count);

    foreach (ManagementObject printManagementObject in results)
    {
        InstalledPrinter entry = new InstalledPrinter();

        foreach (PropertyInfo propertyInfo in typeof(InstalledPrinter).GetProperties()) {
            object[] oparams = {1};
            if (propertyInfo.Name != "IsDefault") {//The IsDefault property is worked out logically, the rest of the properties map identically to the columns of the WMI query results.
                try {
                    oparams[0] = ConvertValue(
                        printManagementObject[propertyInfo.Name], propertyInfo.PropertyType);
                    propertyInfo.GetSetMethod().Invoke(
                        entry,
                        oparams);
                }catch(Exception e) {
                    _s_logger.Error(string.Format("Failed to enumerate printer property Name:{0}, Type:{1}", propertyInfo.Name, propertyInfo.PropertyType));
                }
            }
        }
        _s_logger.Info(string.Format("Finished enumerating properties of printer: {0}", entry.Name == null ? "<Null>" : entry.Name));
        if (sDefault.Equals(entry.Name, StringComparison.CurrentCultureIgnoreCase)) {
            entry.IsDefault = true;
        }
        list.Add(entry);
    }
    return list;
}

private static object ConvertValue(object value, Type type)
{
    if (value != null)
    {
        object printerStatusRetval = null;
        if (type == typeof(DateTime))
        {
            string time = value.ToString();
            time = time.Substring(0, time.IndexOf("."));
            return DateTime.ParseExact(time, "yyyyMMddHHmmss", null);
        }
        else if (type == typeof(long))
            return Convert.ToInt64(value);
        else if (type == typeof(int))
            return Convert.ToInt32(value);
        else if (type == typeof(short))
            return Convert.ToInt16(value);
        else if (type == typeof(string))
            return value.ToString();
        else if (type == typeof(PrinterStatus))
            try {
                printerStatusRetval = Enum.Parse(typeof (PrinterStatus), value.ToString());
            } catch (Exception e) {
                _s_logger.Error(string.Format("Failed to convert PrinterStatus with value {0}", value));
                printerStatusRetval = value.ToString();
            }
                return printerStatusRetval;
    }
    return null;
}

}

...then after instantiating Word I have something like this to set the printer:

            object[] oWordDialogParams = {PreferredPrinter.Name, true};
            object[] oWordDialogParamsWithPort = {string.Format("{0} on {1}", PreferredPrinter.Name, PreferredPrinter.PortName), true};
            string[] argNames = {"Printer", "DoNotSetAsSysDefault"};
//oWord is my own class that provides a fairly simple wrapper around MS Word
            oWord.Application.ActivePrinter = UserSettings[SETTING_PREFERRED_PRINTER] as string;
            Dialog printDialog = oWord.Application.Dialogs[WdWordDialog.wdDialogFilePrintSetup];
            object wordBasic = oWord.Application.WordBasic;
            try {
                wordBasic.GetType().InvokeMember("FilePrintSetup"
                    , BindingFlags.InvokeMethod
                    , null
                    , wordBasic
                    , oWordDialogParams
                    , null
                    , null
                    , argNames);
            }catch(Exception e) {
                _s_logger.Info("Failed to print using printer name, trying printer name and port", e);
                try {
                    wordBasic.GetType().InvokeMember("FilePrintSetup"
                        , BindingFlags.InvokeMethod
                        , null
                        , wordBasic
                        , oWordDialogParamsWithPort
                        , null
                        , null
                        , argNames);
                }catch(Exception e2) {
                    _s_logger.Info("Failed to print using printer name and port", e2);
                    throw;
                }
            }

这篇关于Microsoft Word中互操作的自动化FilePrintSetup错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 09:03