C++ 之 cli窗口交互程序测试DLL

C++ 之 cli窗口交互程序测试DLL

  • 在进行cmd窗口调用DLL时,根据用户不同的输入相应的执行不同的接口进行测试,支持多线程测试:

    • C++ 测试dll程序
    • C# 测试dll程序

1. C++实现

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>  // 用于Windows平台的键盘输入检测
#include <windows.h> // 用于Sleep函数

// 示例接口函数
void startFunction() {
    printf("启动功能已调用!\n");
    // 这里可以添加实际的启动代码
}

void stopFunction() {
    printf("停止功能已调用!\n");
    // 这里可以添加实际的停止代码
}

void pauseFunction() {
    printf("暂停功能已调用!\n");
    // 这里可以添加实际的暂停代码
}

void resumeFunction() {
    printf("恢复功能已调用!\n");
    // 这里可以添加实际的恢复代码
}

void exitFunction(int *running) {
    printf("退出程序...\n");
    *running = 0;
}

// 显示帮助信息
void showHelp() {
    printf("\n=== 键盘按键交互测试程序 ===\n");
    printf("按键映射:\n");
    printf("  S/s - 启动功能\n");
    printf("  T/t - 停止功能\n");
    printf("  P/p - 暂停功能\n");
    printf("  R/r - 恢复功能\n");
    printf("  H/h - 显示帮助\n");
    printf("  Q/q - 退出程序\n");
    printf("============================\n\n");
}

int main() {
   
    int running = 1;
    showHelp();
    
    printf("程序已启动,请按相应键进行测试...\n");
    
    while (running) {
        // 检查是否有按键按下
        if (_kbhit()) {
            char key = _getch();
            
            // 处理按键
            switch (key) {
                case 'S':
                case 's':
                    startFunction();
                    break;
                case 'T':
                case 't':
                    stopFunction();
                    break;
                case 'P':
                case 'p':
                    pauseFunction();
                    break;
                case 'R':
                case 'r':
                    resumeFunction();
                    break;
                case 'H':
                case 'h':
                    showHelp();
                    break;
                case 'Q':
                case 'q':
                    exitFunction(&running);
                    break;
                default:
                    printf("未定义的按键: %c (按H查看帮助)\n", key);
                    break;
            }
        }
        
        // 短暂休眠以减少CPU占用
        Sleep(100);
    }
    
    printf("程序已退出。\n");
    return 0;
}

C#

using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Collections.Generic;

public class NativeMethods
{
    // 假设的C++ DLL接口 - 请根据实际DLL修改
    [DllImport("YourCppDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void StartOperation(int operationId);
    
    [DllImport("YourCppDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void StopOperation(int operationId);
    
    [DllImport("YourCppDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int GetOperationStatus(int operationId);
    
    [DllImport("YourCppDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void Initialize();
    
    [DllImport("YourCppDll.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern void Cleanup();
}

class Program
{
    private static bool isRunning = true;
    private static Dictionary<ConsoleKey, int> keyMapping = new Dictionary<ConsoleKey, int>();

    static void Main(string[] args)
    {
        // 初始化键位映射(可以根据需要修改)
        InitializeKeyMapping();
        
        Console.WriteLine("=== 实时线程控制程序 ===");
        Console.WriteLine("按键映射:");
        foreach (var mapping in keyMapping)
        {
            Console.WriteLine($"{mapping.Key}: 控制操作{mapping.Value}");
        }
        Console.WriteLine("Space: 显示状态");
        Console.WriteLine("ESC: 退出程序");
        Console.WriteLine("==========================");
        
        // 初始化DLL(如果有需要的话)
        try
        {
            NativeMethods.Initialize();
            Console.WriteLine("DLL初始化成功");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"DLL初始化失败: {ex.Message}");
        }

        // 设置控制台以便实时读取按键
        Console.TreatControlCAsInput = true;
        Console.CursorVisible = false;

        // 主循环 - 实时检测键盘输入
        while (isRunning)
        {
            if (Console.KeyAvailable)
            {
                ProcessKeyPress();
            }
            
            // 短暂休眠以减少CPU使用率
            Thread.Sleep(10);
        }

        // 清理资源
        try
        {
            NativeMethods.Cleanup();
            Console.WriteLine("DLL清理完成");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"DLL清理错误: {ex.Message}");
        }

        Console.WriteLine("程序已退出");
        Console.CursorVisible = true;
    }

    static void InitializeKeyMapping()
    {
        // 定义按键与操作ID的映射关系
        keyMapping[ConsoleKey.D1] = 1;  // 按1键控制操作1
        keyMapping[ConsoleKey.D2] = 2;  // 按2键控制操作2
        keyMapping[ConsoleKey.D3] = 3;  // 按3键控制操作3
        keyMapping[ConsoleKey.D4] = 4;  // 按4键控制操作4
        // 可以继续添加更多映射...
    }

    static void ProcessKeyPress()
    {
        ConsoleKeyInfo keyInfo = Console.ReadKey(true);
        
        switch (keyInfo.Key)
        {
            case ConsoleKey.Escape:
                isRunning = false;
                Console.WriteLine("\n退出程序...");
                break;
                
            case ConsoleKey.Spacebar:
                ShowAllStatus();
                break;
                
            default:
                if (keyMapping.ContainsKey(keyInfo.Key))
                {
                    int operationId = keyMapping[keyInfo.Key];
                    ToggleOperation(operationId);
                }
                else
                {
                    Console.WriteLine($"\n未知按键: {keyInfo.Key}");
                }
                break;
        }
    }

    static void ToggleOperation(int operationId)
    {
        try
        {
            int status = NativeMethods.GetOperationStatus(operationId);
            
            if (status == 0) // 假设0表示停止状态
            {
                NativeMethods.StartOperation(operationId);
                Console.WriteLine($"\n启动操作 {operationId}");
            }
            else
            {
                NativeMethods.StopOperation(operationId);
                Console.WriteLine($"\n停止操作 {operationId}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\n操作 {operationId} 执行失败: {ex.Message}");
        }
    }

    static void ShowAllStatus()
    {
        Console.WriteLine("\n=== 当前状态 ===");
        foreach (var mapping in keyMapping)
        {
            try
            {
                int status = NativeMethods.GetOperationStatus(mapping.Value);
                string statusText = status == 0 ? "停止" : "运行中";
                Console.WriteLine($"操作 {mapping.Value}: {statusText}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"操作 {mapping.Value}: 状态获取失败 - {ex.Message}");
            }
        }
        Console.WriteLine("================");
    }

    // 如果需要处理控制台关闭事件
    [DllImport("Kernel32")]
    private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
    private delegate bool EventHandler(CtrlType sig);
    private static EventHandler _handler;

    enum CtrlType
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT = 1,
        CTRL_CLOSE_EVENT = 2,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT = 6
    }

    private static bool Handler(CtrlType sig)
    {
        Console.WriteLine("正在关闭程序...");
        isRunning = false;
        Thread.Sleep(1000); // 给清理操作一些时间
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月醉窗台

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值