简体   繁体   English

Win32:使用cchTextMax在树视图中设置文本长度

[英]Win32: Set text length in Tree View with cchTextMax

Is it possible to define text length that would be displayed in the node of Tree View control in Win32 application? 是否可以定义将在Win32应用程序的“树形视图”控件的节点中显示的文本长度?

For example we have string "text|2". 例如,我们有字符串“ text | 2”。 Then I want to store pointer to this string in the node, but display only "text" without "|2". 然后,我想将指向此字符串的指针存储在节点中,但仅显示“ text”而不显示“ | 2”。

I thought that cchTextMax field is responsible for this, but the next code won't work: 我以为cchTextMax字段对此负责,但是下一个代码将不起作用:

TV_INSERTSTRUCT tvinsert;
tvinsert.item.mask = TVIF_TEXT;
tvinsert.item.pszText = "text|2";
tvinsert.item.cchTextMax= 4;
SendDlgItemMessage(hDlg,IDD_TREE,TVM_INSERTITEM,0,(LPARAM)&tvinsert);

Node strill displays full text "text|2". 节点strill显示全文“ text | 2”。

One solution was to copy required text to new pointer, and then use it. 一种解决方案是将所需的文本复制到新的指针,然后使用它。 But this solution not satisfied me, since I need to store last part of string with node too. 但是这个解决方案令我不满意,因为我也需要将字符串的最后一部分与节点一起存储。

Here is from MSDN documentation of TVITEM : 这是来自TVITEM的 MSDN文档:

cchTextMax cchTextMax
Size of the buffer pointed to by the pszText member, in characters. pszText成员指向的缓冲区大小,以字符为单位。 If this structure is being used to set item attributes, this member is ignored. 如果此结构用于设置项目属性,则将忽略此成员。

So this member is only valid when you are retrieving an items attribute and ignored when you are setting it(as in adding a new item to a tree-view control). 因此,该成员仅在检索 items属性时有效,而在设置时被忽略 (如在向树视图控件中添加新项目时)。 Your other solution of copying required text to new pointer, and then using is one option. 将必需的文本复制到新的指针,然后使用的另一种解决方案是一个选项。

Strings in C are null terminated char arrays, that is, Windows will display any chars up to the first '\\0' it met, there is no way to specify length. C中的字符串是以null终止的char数组,也就是说,Windows将显示直到遇到的第一个'\\ 0'的所有char,无法指定长度。 In order to do what you want, you have to create a new string: 为了做您想要的,您必须创建一个新的字符串:

const char *s = "text|2";
const char str_to_display[5] = {'\0'};
strncpy(str_to_display, s, 4);

I would extend fluter's answer, and to insert that '\\0' right in place of the separator. 我会扩展fluter的答案,并在分隔符'\\0'右边插入'\\0' A typical use of this is multi-string, where you have a set of 0-terminated string together, terminated with double '\\0' . 此方法的典型用法是多字符串,其中您具有一组以0终止的字符串,并以双'\\0'终止。

As a side benefit, you can use strtok() to parse your string; 作为附带的好处,您可以使用strtok()来解析您的字符串。 the (sometimes undesirable) effect of it is insertion of zeroes in place of separators. 它的效果(有时是不希望的)是插入零代替分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM