Help test your code and come up with a fix

147 views
Skip to first unread message

VN

unread,
Jun 14, 2023, 6:32:34 PM6/14/23
to Programmers
This topic is managed by Ai Robot, I will turn it on only in this topic, to avoid it replying in other threads. if you need to test your code, and want AI robot to come up with a fix. then please post your code here. it can deal with all programming languages, as well as help you to compile from one programming language to another.

phục hoangphuc

unread,
Jun 15, 2023, 8:50:47 AM6/15/23
to Programmers
please help me check the code and fix it properly


import win32gui, win32con



hwnd_send = 0

room_list = []





def init_room_list_cb(hwnd, lparam):

    name = win32gui.GetClassName(hwnd)



    if name == "DlgGroupChat Window Class":

        global room_list

        room_list.append(win32gui.GetWindowText(hwnd))





def init_room_list():

    win32gui.EnumWindows(init_room_list_cb, 0)



    if not room_list:

        print("No rooms found")





def dlg_group_chat_cb(hwnd, lparam):

    name = win32gui.GetClassName(hwnd)

    global hwnd_send



    if name == "RichEdit20W":

        hwnd_send = hwnd





def init_room_hwnd(room_name):

    window = win32gui.FindWindow("DlgGroupChat Window Class", room_name)

    win32gui.EnumChildWindows(window, dlg_group_chat_cb, 0)





def send_text(text):

    win32gui.SendMessage(hwnd_send, win32con.WM_SETTEXT, 0, text.encode('ascii'))





def getAskingForMicrophone():

    memberIndex = 0

    isAskingForMicrophone = win32gui.SendMessage(hwnd_send, win32con.WM_USER + 1, memberIndex, 0)

    print("isAskingForMicrophone", isAskingForMicrophone)



if __name__ == '__main__':

    init_room_list()

    print("Rooms:", room_list)

    init_room_hwnd(room_list[0])

    send_text("Connected to the room: " + room_list[0])

    getAskingForMicrophone()


Vào lúc 05:32:34 UTC+7 ngày Thứ Năm, 15 tháng 6, 2023, VN đã viết:

RobotAI

unread,
Jun 15, 2023, 9:14:30 AM6/15/23
to Programmers
This code uses the win32gui and win32con libraries to interact with windows on the Windows operating system. It searches for windows whose class name is "DlgGroupChat Window Class" and stores their title in the room_list. It then looks for a subwindow with the class name "RichEdit20W" and stores its hwnd value in the hwnd_send variable. Finally, it sends a message to this window using the SendMessage function with the WM_SETTEXT message.

I can't run this code to check if it's working correctly, but it looks like it's syntactically written. However, you should check that the values of the class names and messages are appropriate for the application you are trying to interact with. If you get any errors while running this code, let me know and I will try to help you.

Also, I have some suggestions to improve this piece of code:

Avoid using global variables: Instead of using global variables like hwnd_send and room_list, you can pass them as parameters to functions and return them from functions. This will help reduce dependencies between functions and make the code easier to read and maintain.
Use docstrings: You can add docstrings at the beginning of each function to describe their purpose and usage. This will help your readers better understand your code.
Snippet formatting: You can use an automatic code-formatting tool, such as black or autopep8, to reformat your code according to Python's standard rules. This will make your code easy to read and follow the general style rules.
Hope these suggestions help you improve your code! If you have any other questions, please let me know.

Here's an improved version of the code snippet you've provided. I've applied some of my suggestions to improve the code snippet. However, I can't run this code to check if it's working correctly, so you should test it before using it.

import win32gui
import win32con


def init_room_list():
    """Find all windows with the class name 'DlgGroupChat Window Class' and return their titles."""

    room_list = []

    def init_room_list_cb(hwnd, lparam):
        name = win32gui.GetClassName(hwnd)
        if name == 'DlgGroupChat Window Class':
            room_list.append(win32gui.GetWindowText(hwnd))


    win32gui.EnumWindows(init_room_list_cb, 0)

    if not room_list:
        print('No rooms found')

    return room_list


def init_room_hwnd(room_name):
    """Find the child window with the class name 'RichEdit20W' and return its hwnd value."""
    hwnd_send = 0

    def dlg_group_chat_cb(hwnd, lparam):
        nonlocal hwnd_send
        name = win32gui.GetClassName(hwnd)
        if name == 'RichEdit20W':
            hwnd_send = hwnd


    window = win32gui.FindWindow('DlgGroupChat Window Class', room_name)
    win32gui.EnumChildWindows(window, dlg_group_chat_cb, 0)

    return hwnd_send


def send_text(hwnd_send, text):
    """Send a text message to the specified window."""

    win32gui.SendMessage(hwnd_send, win32con.WM_SETTEXT, 0,
                         text.encode('ascii'))


def getAskingForMicrophone(hwnd_send):
    """Check if a member is asking for the microphone."""

    memberIndex = 0
    isAskingForMicrophone = win32gui.SendMessage(hwnd_send,
            win32con.WM_USER + 1, memberIndex, 0)
    print('isAskingForMicrophone', isAskingForMicrophone)


if __name__ == '__main__':
    room_list = init_room_list()
    print('Rooms:', room_list)
    hwnd_send = init_room_hwnd(room_list[0])
    send_text(hwnd_send, 'Connected to the room: ' + room_list[0])
    getAskingForMicrophone(hwnd_send)

Vào lúc 19:50:47 UTC+7 ngày Thứ Năm, 15 tháng 6, 2023, phục hoangphuc đã viết:

phục hoangphuc

unread,
Jun 15, 2023, 9:22:46 AM6/15/23
to Programmers
thanks RobotAI, Can you explain to me the above code ?, and your code has just been fixed.

Vào lúc 20:14:30 UTC+7 ngày Thứ Năm, 15 tháng 6, 2023, RobotAI đã viết:

RobotAI

unread,
Jun 15, 2023, 9:23:25 AM6/15/23
to Programmers
This is an improved version of the code you provided. I applied some of my suggestions to improve the code. This code uses the win32gui and win32con libraries to interact with windows on the Windows operating system.

The init_room_list function searches for windows with a class name of "DlgGroupChat Window Class" and stores their title in the room_list. This function returns the list of rooms found.

The init_room_hwnd function takes a room_name parameter and looks for a subwindow with the class name "RichEdit20W" in the window titled room_name. This function returns the hwnd value of the child window found.

The send_text function takes two parameters: hwnd_send and text. This function sends a message to the window with hwnd value hwnd_send using the SendMessage function with the WM_SETTEXT message.

The getAskingForMicrophone function takes an hwnd_send parameter and checks if any member is requesting a microphone. This function prints the test results.

The last code in the if __name__ == '__main__' block: calls the above functions to search the list of rooms, select the first room, send a message to that room and check if any member is requesting the microphone. or not.

Hope this explanation helps you to understand my code better! If you have any other questions, please let me know.
Vào lúc 20:22:46 UTC+7 ngày Thứ Năm, 15 tháng 6, 2023, phục hoangphuc đã viết:

phục hoangphuc

unread,
Jun 15, 2023, 10:38:42 AM6/15/23
to Programmers
Thank you very much

Vào lúc 20:23:25 UTC+7 ngày Thứ Năm, 15 tháng 6, 2023, RobotAI đã viết:

RobotAI

unread,
Jun 15, 2023, 10:40:10 AM6/15/23
to Programmers
You’re welcome! Is there anything else you would like to know? 

Vào lúc 21:38:42 UTC+7 ngày Thứ Năm, 15 tháng 6, 2023, phục hoangphuc đã viết:

KháchQuaĐường

unread,
Jun 16, 2023, 6:29:57 AM6/16/23
to Programmers
Hello RobotAI,  I want to use SendMessageW to send a message to RichEdit20W a message containing Vietnamese accents and icons in c# language. and  I need to send message containing icon and unicode to paltalt through RichEdit20W i am getting font error like this “Xin chᅢᅠo! ᅣミᅢᄁy lᅢᅠ m£ᄏルt tin nh£ᄎᆵn Unicode ti£ᄎ﾿ng Vi£ᄏヌt cᅢᄈ d£ᄎᆬu￯﾿ᄑ￯﾿ᄑ” can anyone help me. Thanks

Vào lúc 21:40:10 UTC+7 ngày Thứ Năm, 15 tháng 6, 2023, RobotAI đã viết:

RobotAI

unread,
Jun 16, 2023, 7:16:54 AM6/16/23
to Programmers
Hello  KháchQuaĐường
You can use the `SendMessageW` function to send a message to a RichEdit20W control in C#. This function sends the specified message to a window or windows and calls the window procedure for the specified window, not returning until the window procedure has processed the message¹.

Here is an example of how you might use `SendMessageW` to send a message containing Vietnamese text with accents to a RichEdit20W control:


```csharp
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

const uint WM_SETTEXT = 0x000C;

// hWnd is the handle to the RichEdit20W control
string text = "Xin chào! Đây là một tin nhắn Unicode tiếng Việt có dấu";
IntPtr ptr = Marshal.StringToHGlobalUni(text);
SendMessage(hWnd, WM_SETTEXT, IntPtr.Zero, ptr);
Marshal.FreeHGlobal(ptr);
```

This code uses the `WM_SETTEXT` message to set the text of the RichEdit20W control. The text is first converted to a pointer using `Marshal.StringToHGlobalUni` and then passed as the `lParam` parameter of the `SendMessage` function.

As for sending icons, you may need to use Rich Text Format (RTF) to insert images into the RichEdit20W control. You can find more information on how to do this in C# by searching online.
It seems that you are having trouble getting a RichEdit control to display unicode RTF text. One solution could be to use **UTF-8**, which is an 8-bit encoding but still can represent the full range of Unicode characters. You can get UTF-8 from a PWSTR via **WideCharToMultiByte()**¹. Once you have it in UTF-8, you can use the **EM_SETTEXTEX** parameter with the **codepage** set to **CP_UTF8**¹.



PWSTR stands for Pointer to Wide STRing and is used to represent a pointer to a null-terminated string of 16-bit Unicode characters.

WideCharToMultiByte() is a function that maps a wide-character string to a new character string. The new character string is not necessarily from a multibyte character set.

EM_SETTEXTEX is a message that sets the text of a rich edit control and specifies the character set and code page used to interpret the text.


RichEdit20A and RichEdit20W are two versions of the Rich Edit control. The A and W at the end of the names stand for ANSI and Unicode respectively. The main difference between the two is that RichEdit20A uses ANSI character encoding while RichEdit20W uses Unicode character encoding. This means that RichEdit20A can only display characters from the Windows character set while RichEdit20W can display characters from multiple character sets.


Here is an example of how you can get UTF-8 from a PWSTR via WideCharToMultiByte():

PWSTR WideString = /* Some string... */;
DWORD WideLength = wcslen(WideString) + 1;
PSTR Utf8;
DWORD Length;
INT ReturnedLength;

// A utf8 representation shouldn't be longer than 4 times the size
// of the utf16 one.
Length = WideLength * 4;
Utf8 = (PSTR)malloc(Length);
if (!Utf8) {
    /* TODO: handle failure */
}

ReturnedLength = WideCharToMultiByte(
    CP_UTF8,
    0,
    WideString,
    WideLength - 1,
    Utf8,
    Length - 1,
    NULL,
    NULL
);
if (ReturnedLength) {
    // Need to zero terminate...
    Utf8[ReturnedLength] = 0;
} else {
    /* TODO: handle failure */
}

Once you have it in UTF-8, you can do this:

SETTEXTEX TextInfo = {0};

TextInfo.flags = ST_SELECTION;
TextInfo.codepage = CP_UTF8;

SendMessage(hRichText, EM_SETTEXTEX, (WPARAM)&TextInfo, (LPARAM)Utf8);
Copy
And of course, don’t forget to free the memory allocated for Utf8:

free(Utf8);



PWSTR stands for Pointer to Wide STRing and is used to represent a pointer to a null-terminated string of 16-bit Unicode characters.

WideCharToMultiByte() is a function that maps a wide-character string to a new character string. The new character string is not necessarily from a multibyte character set.

EM_SETTEXTEX is a message that sets the text of a rich edit control and specifies the character set and code page used to interpret the text.


RichEdit20A and RichEdit20W are two versions of the Rich Edit control. The A and W at the end of the names stand for ANSI and Unicode respectively. The main difference between the two is that RichEdit20A uses ANSI character encoding while RichEdit20W uses Unicode character encoding. This means that RichEdit20A can only display characters from the Windows character set while RichEdit20W can display characters from multiple character sets.


(1) SendMessageW function (winuser.h) - Win32 apps | Microsoft Learn. https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessagew.
(2) c# - Sending Colored Text to richedit20w - Stack Overflow. https://stackoverflow.com/questions/6746833/sending-colored-text-to-richedit20w.
(3) c# - Find control of specific class in another application - Stack Overflow. https://stackoverflow.com/questions/28672384/find-control-of-specific-class-in-another-application.


(1) mfc - Unicode RTF text in RichEdit - Stack Overflow. https://stackoverflow.com/questions/1782409/unicode-rtf-text-in-richedit.
(2) About Rich Edit Controls - Win32 apps | Microsoft Learn. https://learn.microsoft.com/en-us/windows/win32/controls/about-rich-edit-controls.
(3) MS Rich Edit Control ("RICHEDIT50W") bug? Control does unnecessary font .... https://learn.microsoft.com/en-us/answers/questions/1118485/ms-rich-edit-control-%28richedit50w%29-bug-control-doe.

Would you like more information on this topic?

Vào lúc 17:29:57 UTC+7 ngày Thứ Sáu, 16 tháng 6, 2023, KháchQuaĐường đã viết:

phục hoangphuc

unread,
Jun 16, 2023, 7:22:13 AM6/16/23
to Programmers
chào người bạn việt nam, bạn vào đây tham khảo file đính kèn Program.cs. coi có giải quyết được vụ gữi tin nhắn vào phòng không. tui cũng đang ngâm cứu
https://groups.google.com/g/developerpaltalk/c/qJgGt4IvL2A/m/WSoJG_hDAAAJ

Vào lúc 18:16:54 UTC+7 ngày Thứ Sáu, 16 tháng 6, 2023, RobotAI đã viết:

VN

unread,
Jun 16, 2023, 7:57:10 AM6/16/23
to Programmers
Để cho RobotAI trả lời một cách chính xác hơn, các bạn nên copy đoạn mã của mình vào đây, và nêu ra những lỗi mình gặp, cũng như dữ liệu đầu vào, dữ liệu cuối .v.vv các bạn đưa ra những điều kiện rõ ràng thì câu trả lời sẽ chính xác hơn. Nhưng nó chỉ là một câu trả lời tham khảo cho mình học hỏi thêm. các bạn dựa vào đó để xây dựng. đừng mong muốn là phải đúng 100%.  Thanks
Reply all
Reply to author
Forward
0 new messages