控制台程序在C#下调用;关于MFC的初始化

文章讲述了在使用MFC编写控制台程序后,在C#环境中通过Process调用时遇到的MFC未初始化问题。错误源于afxCurrentInstanceHandle未初始化。解决方案是通过在控制台程序的主函数中调用AfxWinInit进行MFC初始化。示例代码展示了如何在主函数中正确调用AfxWinInit进行初始化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近用MFC写了一个控制台程序,然后在C#环境下用个Process来调用,出现如下错误:

afxwin1.inl assert at line:22
现象:打开afxwin1.inl 发现 assert(afxCurrentInstanceHandle != NULL)出错
说明MFC没有做初始化,afxCurrentInstanceHandle没有初始化。解决办法如下:见红色部分
 

#include "parse.h"

#include "iostream.h"

#include "afxwin.h"  //afxWinInit对应的头文件

int main(int argc, char* argv[])

{

    AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0); //控制台程序中初始化MFC

CParse parse;

if (argc==2 && !strcmp(argv[1],"a")){       

parse.OnExtractUnb();

}

else if (argc==2 && !strcmp(argv[1], "b")) {

parse.OnExtractAll();

}

else

{

MessageBox(NULL,"输入参数错误!","信息提示",MB_OK);

}

return 0;


AfxWinInit
BOOL AFXAPI AfxWinInit( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )

Parameters

hInstance

The handle of the currently running module.

hPrevInstance

A handle to a previous instance of the application.  For a Win32-based application, this parameter is always NULL.

lpCmdLine

Points to a null-terminated string specifying the command line for the application.

nCmdShow

Specifies how the main window of a GUI application would be shown.

Remarks

This function is called by the MFC-supplied WinMain function, as part of the CWinApp initialization of a GUI-based application, to initialize MFC. For a console application, which does not use the MFC-supplied WinMain function, you must call AfxWinInit directly to initialize MFC.

If you call AfxWinInit yourself, you should declare an instance of a CWinApp class. For a console application, you might choose not to derive your own class from CWinApp and instead use an instance of CWinApp directly. This technique is appropriate if you decide to leave all functionality for your application in your implementation of main.

The  TEAR sample shows how to make a console application using MFC.

Example

// this file must be compiled with the /GX and /MT options:
//      cl /GX /MT thisfile.cpp
 
#include <afx.h>
#include <afxdb.h>
#include <iostream.h>
 
int main()
{
   // try to initialize MFC
 
   if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值