簡體   English   中英

我可以在main()函數之外使用GetAsyncKeyState()嗎?

[英]Can I use GetAsyncKeyState() outside of the main() function?

我在寫,只是為了對編程過程有信心,它是一個響應鍵盤輸入的Win32應用程序。 為此,我正在使用GetAsyncKeyState()函數。

最初,我在main()函數中編寫了所有代碼,而且看起來都不錯,它可以正常工作。 所以我決定的事情復雜化,但這需要我用GetAsyncKeyState()函數被調用不同的功能main() 我以為我只需要在main()外部聲明一些變量,然后將代碼從main移到新函數,如下所示:

int btnup_down = 0; 
int close = 1; 
int main(void){
    while (1){
        Sleep(50);
        listentokb();
        if (close == 0){
            break;
        }
    }return 0;
}
int listentokb(void){ 
    if ((GetAsyncKeyState(0x4C) & 0x8000) && (ko == 0)){ 
        ko = 1; 
        printf("Ok you pressed k"); 
        return 0; 
    } else if (((GetAsyncKeyState(0x4C) == 0) && (ko == 1))  { 
        ko = 0; 
        printf("Now you released it"); 
        close = 0; 
        return 0; 
    }return 0; 
}

當我運行此代碼時,循環繼續進行,無論是否按下鍵都無關緊要,循環不斷進行而無需打印任何內容。 任何幫助將不勝感激。

您的問題與main()無關。 您可以在代碼中的任意位置調用winapi函數,例如GetAsyncKeyState() ,只要您提供了合適的參數即可。

根據此虛擬鍵控代碼列表,代碼0x4c對應於鍵L而不對應於鍵K。 因此,在您的代碼中輸入括號校正錯誤后,我可以成功地將其與L循環插入

關於您的功能的一些評論:

您的函數listentokb()始終返回0。另一方面,您使用全局變量close告訴調用函數鍵盤掃描的結果。 這是非常糟糕的做法:盡可能避免使用全局變量。

這里是代碼的略微更新的版本,該版本禁止全局變量,並使用返回值來傳達結果:

const int KEY_K = 0x4B;    // avoid using values directly in the code

int listentokb (void){  // returns 'K' if K is released and 0 otherwise
    static int ko;      // this is like a global variable: it will keep the value from one call to the other
                        // but it has teh advantage of being seen only by your function
    if((GetAsyncKeyState(KEY_K) & 0x8000) && (ko == 0)){
        ko = 1;
        printf("Ok you pressed k");
        return 0;
    }
    else if((GetAsyncKeyState(KEY_K) == 0) && (ko == 1))  {
        ko = 0;
        printf("Now you released it");
        return 'K'; 
    }
    return 0;
}
int main(void){
    bool go_on = true;   // The state of the loop shall be local variable not global
    while(go_on){
        Sleep(50);
        go_on= ! listentokb();  // if returns 0  we go on
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM