-1

我正在为我的 Now Playing 插件获取 Spotify 的窗口标题,其中包含以下功能:

GetWindowText(spotify_window_handle, title, title_length)

但输出包含替换字符 \uFFFD。

Ex. Spotify - Killswitch Engage � One Last Sunset

如何在 C 中用 - 替换 �?

下面是完整代码:

char* spotify_title(int window_handle)
{
    int title_length = GetWindowTextLength(window_handle);
        if(title_length != 0)
        {
            char* title;
            title = (char*)malloc((++title_length) * sizeof *title );
            if(title != NULL)
            {
                GetWindowText(window_handle, title, title_length);
                if(strcmp(title, "Spotify") != 0)
            {
                return title;
            }
            else
            {
                return "Spotify is not playing anything right now. Type !botnext command to restart playback.";
            }
        }
        else
        {
            printf("PLUGIN: Unable to allocate memory for title\n");
        }
        free(title);
    }
    else
    {
        printf("PLUGIN: Unable to get Spotify window title\n");
    }
}
// End of Spotify get title function
4

3 回答 3

1

在 Unicode->Ansi 转换期间使用替换字符。在没有看到title实际声明的方式(是使用char还是wchar_t?)的情况下,我的猜测是您正在调用GetWindowText()(aka GetWindowTextA()) 的 Ansi 版本,并且窗口标题包含一个 Unicode 字符,该字符无法在您的操作系统的默认 Ansi 语言环境中表示,因此GetWindowTextA()替换它将窗口文本转换为 Ansi 以进行输出时的字符。请记住,Windows 实际上是基于 Unicode 的操作系统,因此您应该使用GetWindowText()(aka GetWindowTextW()) 的 Unicode 版本,例如:

WCHAR title[256];
int title_length = 256;
GetWindowTextW(spotify_window_handle, title, title_length);

或者:

int title_length = GetWindowTextLengthW(spotify_window_handle);
LPWSTR title = (LPWSTR) malloc((title_length+1) * sizeof(WCHAR));
GetWindowTextW(spotify_window_handle, title, title_length+1);
...
free(title);

或者至少确保您的项目配置为针对 Unicode 进行编译,以便在编译期间UNICODE进行_UNICODE定义。这将使GetWindowText()map toGetWindowTextW()而不是GetWindowTextA(). 然后,您将不得不使用TCHAR您的title缓冲区,例如:

TCHAR title[256];
int title_length = 256;
GetWindowText(spotify_window_handle, title, title_length);

或者:

int title_length = GetWindowTextLength(spotify_window_handle);
LPTSTR title = (LPTSTR) malloc((title_length+1) * sizeof(TCHAR));
GetWindowText(spotify_window_handle, title, title_length+1);
...
free(title);
于 2013-06-12T17:04:14.780 回答
0

这取决于您是否使用 Unicode。既然你说 \uFFFD 你很可能在 Unicode 所以

   WCHAR *wp; 

   while ((wp= wcschr(title, '\uFFFD'))!=NULL) {
       *wp= L'-';
   }
于 2013-06-12T10:52:00.870 回答
0

假设字符串是数组wchar_t

wchar_t * p = wcschr(title, `\uFFFD`);
if (p)
  *p = `\u002D`;
于 2013-06-12T10:53:29.273 回答